如何在 PHP 中从数组添加随机运算符
我写了这个:(
$num1 = mt_rand(1,5);
$num2 = mt_rand(1,5);
$operators = array(
"+",
"-",
"*",
"/"
);
$result = $num1 . $operators[array_rand($operators)] . $num2;
我最好的猜测是)这并不像我预期的那样工作,因为在数组中运算符是一个字符串,它使所有内容都成为字符串:
var_dump($result);
给出:
string(3) "4+3"
所以我的问题是你会建议如何在不改变逻辑太多了?
提前致谢!!
*对随机数进行随机运算,如果可能的话,应将运算符存储在数组中。
我觉得我的标题没有正确描述情况,但我想不出更好的主意,我愿意接受建议:)
I wrote this:
$num1 = mt_rand(1,5);
$num2 = mt_rand(1,5);
$operators = array(
"+",
"-",
"*",
"/"
);
$result = $num1 . $operators[array_rand($operators)] . $num2;
(My best guess is) This doesn't work as I expected because in the array the operator is a string which makes everything a string:
var_dump($result);
Gives:
string(3) "4+3"
So my question would be how would you recommend approaching this* without changing the logic it too much?
Thanks in advance!!
*Making random operation among random numbers, and if possible, the operators should be stored in an array.
I have the feeling my title is not correctly describing the situation but I could not come up with a better idea, I'm open to suggestions :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当然,您可以使用
eval
来执行此操作,但我当然不会满足于这样的解决方案。我建议定义一堆接受两个参数并返回结果的函数,然后对 array_rand 的结果使用 call_user_func_array 。
Of course, you could use
eval
to do this, but I certainly won't settle for such a solution.I'd suggest defining a bunch of functions that take in two params and return a result, then use
call_user_func_array
on the result ofarray_rand
.干净的解决方案是为每个运算符都有一个代码分支,例如,
如果您有更多运算符,则应该创建一个
operator => 的映射。 function
并动态调用函数,例如:当然,不干净(缓慢,潜在危险)的解决方案是使用
The clean solution would be to have a code branch for each operator, e.g.
If you have more operators, you should create a map of
operator => function
and dynamically call the functions, for example:And of course, the unclean (slow, potentially dangerous) solution would be to use eval().
为每个操作创建一个函数,然后存储operator =>;数组中的函数名称。
Create a function for each operation, then store operator => function name in an array.