Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable Operators in PHP

Tags:

operators

php

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

$operator = '+';
foreach($resultSet as $item){
    $result = $item[$this->orderField] . $operator . 1;
    echo $result;
}
like image 354
BenTheDesigner Avatar asked Mar 31 '10 10:03

BenTheDesigner


1 Answers

You could make functions that wrap the operators, 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;
}
like image 156
reko_t Avatar answered Oct 03 '22 06:10

reko_t