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.

nicoschuck
  • 201
  • 3
  • 13

1 Answers1

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.

reza
  • 1,507
  • 2
  • 12
  • 17
  • 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? – nicoschuck Jan 25 '17 at 13:06
  • 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 – reza Jan 25 '17 at 13:10
  • yes thats right the number of operator are realy less. i'll try it and share the result. anyway thanks for your help – nicoschuck Jan 25 '17 at 13:12