1

I want to do some calculations on my website. For that i saved the form on my database. The database looks like that:

FirstValue |   Operator  | SecondValue
------------------------------------
   20      |      +      |   10
   20      |      -      |   10
   10      |      *      |   10
   10      |      /      |   10

Now i want to print the results on php like that:

for($i=0;$i<count($array);$i++)
    echo $array['FirstValue'][$i].$array['Operator'][$i].$array['SecondValue'][$i];

But i get only the strings which includes the form.

7

1 Answer 1

0

The way you execute it not gonna calculate. you have to do the calculation using either switch case or if-else syntax. Here is a implementation using if-else.

function calculate($a,$b,$c)
{
  if($c=='+')
     return $a+$b;
  else if($c=='-')
     return $a-$b;
  else if($c=='*')
     return $a*$b;
  else if($c=='/')
      return $a/$b;

  return 0;

}
$array['FirstValue'] = array(20,20,10,10);
$array['Operator'] = array('+','-','*','/');
$array['SecondValue'] = array(10,10,10,10);

for($i=0;$i<count($array['FirstValue']);$i++)
  echo calculate($array['FirstValue'][$i],$array['SecondValue'][$i],$array['Operator'][$i])."<br />";

BTW count($array) will give value 3, not 4 for your array design. And also your SecondValue and Operator column name in table needed to be altered.

Sign up to request clarification or add additional context in comments.

3 Comments

Hey thanks for your answer. I thought on this way too but its not realy clean in my opinion. If i do something like that on an 10000*100 Matrix for example there would be a lot of compares. What do you think?
i don't thing so. there might be a lot of data in your matrix but number of operator is very less. always there will be + or - or * or /. so you do not need a lot of compare
yes thats right the number of operator are realy less. i'll try it and share the result. anyway thanks for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.