PHP variable statements

Given this example, how would I return the result of the equation, and not as the equation itself as a string?

$operator = '+'; foreach($resultSet as $item){ $result = $item[$this->orderField] . $operator . 1; echo $result; } 
+4
source share
5 answers

You can create functions that wrap statements, or for simplicity just use the bc extension:

 $operator = '+'; $operators = array( '+' => 'bcadd', '-' => 'bcsub', '*' => 'bcmul', '/' => 'bcdiv' ); foreach($resultSet as $item){ $result = call_user_func($operators[$operator], $item[$this->orderField], 1); echo $result; } 
+17
source

To achieve just that, you can use create_function

 $operator = '+'; $func = create_function('$a,$b', "return \$a $operator \$b;"); foreach($resultSet as $item){ $result = $func($item, 1); echo $result; } 

It is possible to use a cleaner solution with lambdas (php5.3 required)

 $func = function($a, $b) { return $a + $b; }; foreach($resultSet as $item){ $result = $func($item, 1); echo $result; } 

See also array_sum, array_reduce

Advanced example with array_reduce and lambdas

 $ary = array( array('foo' => 1, 'bar' => 91), array('foo' => 2, 'bar' => 92), array('foo' => 3, 'bar' => 93), array('foo' => 4, 'bar' => 94), array('foo' => 5, 'bar' => 95), ); $sumOfFoos = array_reduce($ary, function($val, $item) { return $val + $item['foo']; } ); $sumOfBars = array_reduce($ary, function($val, $item) { return $val + $item['bar']; } ); 

The main thing is that instead of "variable operators" (which is impossible in php), you should rather use variable functions (which is possible and much more flexible).

+6
source

You can use eval() , but this is usually a bad idea, as it is a serious potential security kernel (be careful not to let visitors run arbitrary code!).

It can also lead to complex code maintenance.

+2
source

The quick answer is eval (). However, in this exact example, I would simply adjust the possible operations:

 <?php $operator = '+'; foreach($resultSet as $item){ switch($operator){ case '+': $result = $item[$this->orderField] + 1; break; } echo $result; } ?> 
+2
source

Use the eval function for PHP: http://php.net/manual/en/function.eval.php

 $operator = '+'; foreach($resultSet as $item){ $result = $item[$this->orderField] . $operator . 1; eval("\$result = \"$result\";"); echo $result; } 
+1
source

Source: https://habr.com/ru/post/1305649/


All Articles