PHP Use String as Operator

PHP use string as operator

You can use eval() as suggested by @konforce, however the safest route would be something like:

$left = (int)$a;
$right = (int)$b;
$result = 0;
switch($char){

case "*":
$result = $left * $right;
break;

case "+";
$result = $left + $right;
break;
// etc

}

PHP - arithmetic operations using strings as operators

trickery with math:

echo $initial + (($operation == '-') ? -1 : 1) * $unit;

only using addition, but cheating with multiplying by a negative... :)

can we convert a string into a sign in php

You should do an if statement or a switch case one;

example

if ($opt =='+'){
return $val1+$val2;
}else if($opt =='-'){
return $val1-$val2;
} .... etc

How can I use the += operator in PHP for a string?

You are searching for .=:

$str = "";
$str .= "some value";

How to split some numbers and math operator in PHP?

You can try like this - based upon answer elsewhere on stack. Modified the pattern and added the preg_replace so that the results are not affected by spaces in the input string.

$input = '2 + 3 * 7';
$input = '2-5/3.4';

$pttn='@([-/+\*])@';
$out=preg_split( $pttn, preg_replace( '@\s@', '', $input ), -1, PREG_SPLIT_DELIM_CAPTURE );

printf('<pre>%s</pre>',print_r( $out, true ) );

Will output:

Array
(
[0] => 2
[1] => -
[2] => 5
[3] => /
[4] => 3.4
)

Update:

$input = '2 + 5 - 4 / 2.6';

$pttn='+-/*'; # standard mathematical operators
$pttn=sprintf( '@([%s])@', preg_quote( $pttn ) ); # an escaped/quoted pattern

$out=preg_split( $pttn, preg_replace( '@\s@', '', $input ), -1, PREG_SPLIT_DELIM_CAPTURE );

printf('<pre>%s</pre>',print_r( $out, true ) );

outputs:

Array
(
[0] => 2
[1] => +
[2] => 5
[3] => -
[4] => 4
[5] => /
[6] => 2.6
)


Related Topics



Leave a reply



Submit