如何从PHP中的数组添加随机运算符 [英] How to add random operator from array in PHP

查看:144
本文介绍了如何从PHP中的数组添加随机运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这个:

$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);

赠予:

string(3) "4+3"

所以我的问题是您将如何建议在不过度改变其逻辑的情况下实现这一目标?

So my question would be how would you recommend approaching this* without changing the logic it too much?

提前谢谢!

*在随机数之间进行随机运算,如果可能,运算符应存储在数组中.

*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 :)

推荐答案

当然,您可以使用eval进行此操作,但是我当然不会满足于这种解决方案.

Of course, you could use eval to do this, but I certainly won't settle for such a solution.

我建议定义一堆带有两个参数并返回结果的函数,然后对array_rand的结果使用call_user_func_array.

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 of array_rand.

function add($x, $y) { return $x + $y; }
function subtract($x, $y) { return $x - $y; }
function multiply($x, $y) { return $x * $y; }
function divide($x, $y) { return $x / $y; }

$operators = array('add', 'subtract', 'multiply', 'divide');
//...
$result = call_user_func_array($operators[array_rand($operators)], array($x, $y)); 

这篇关于如何从PHP中的数组添加随机运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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