PHP-使用字符串作为运算符的算术运算 [英] PHP - arithmetic operations using strings as operators

查看:71
本文介绍了PHP-使用字符串作为运算符的算术运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串变量 $ operation ,它可以具有 + -之类的值和两个整数变量 $ initial $ unit .

I have a string variable, $operation, that can have values like + or - and two integer variables $initial and $unit.

所以要回显它们之间的算术运算结果

So to echo the result of the arithmetic operation between them

我必须使用类似的东西

 if($operation == '+') echo ($initial + $unit);
 if($operation == '-') echo ($initial - $unit);

有没有IF的方法吗?

推荐答案

数学难题:

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

仅使用加法,但通过乘以负数来作弊...:)

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

这篇关于PHP-使用字符串作为运算符的算术运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆