0
$operators = array(
    "+",
    "-",
    "*",
    "/"
);

foreach($operators as $key => $opp){
    //echo "key: $key, opperator: $opp <br />";
    echo $result = 4 . $opp . 4 . "<br />";
}

why isn't my code counting the possible combinations?

like:

echo $result = 4 + 4;

8

vdhmartijn
  • 106
  • 2
  • 11

3 Answers3

2

Dot (".") is concatenation operator for strings in PHP. Dynamic typization makes all this a string. Actually you get same as:

echo $result = "4 + 4 <br />";

Use eval as said in prev answer.

foreach($operators as $key => $opp){
    echo $result = eval("echo 4 $opp 4;") . "<br />"; // eval should contain valid code
}
2

You can avoid eval using some anon functions, 5.3+ required

$operators = array(
    "+" => function($l,$r) { return $l + $r; },
    "-" => function($l,$r) { return $l - $r; },
    "*" => function($l,$r) { return $l * $r; },
    "/" => function($l,$r) { return $l / $r; },
);

foreach($operators as $key => $opp){
    //echo "key: $key, opperator: $opp <br />";
    echo $result = $opp(4,4). "<br />";
}
Matthew Scragg
  • 4,540
  • 3
  • 19
  • 27
1

Because you are just doing something with strings. They're not treated as operators.

You could of course use eval:

$x = eval(4 . $opp . 4 );
echo $x;
Jelle Ferwerda
  • 1,254
  • 1
  • 7
  • 13