具有值的动态数组名称

时间:2018-11-17 12:40:45

标签: php arrays

我将数组作为box1 box2等...我正在尝试查找任意2个随机数组之间的公共元素/值...但是我不断收到错误消息target1和target2不是数组,这是我的代码:-< / p>

$box1=array("1","2","3","4","7","9");
$box2=array("11","2","34","4","72","9");
$box3=array("13","42","3","64","7","89");
$box4=array("71","24","38","43","7","19");
$box5=array("1","52","37","94","7","79");

$nos1=rand(1,5);
$nos2=rand(1,5);

$target1="$box".$nos1;
$target1="$box".$nos2;
$common=array();
$common=array_intersect($target1,$target2);

2 个答案:

答案 0 :(得分:2)

您正在分配随机框以错误的方式定位。使用以下代码:

$box1=array("1","2","3","4","7","9");
$box2=array("11","2","34","4","72","9");
$box3=array("13","42","3","64","7","89");
$box4=array("71","24","38","43","7","19");
$box5=array("1","52","37","94","7","79");

$nos1=rand(1,5);
$nos2=rand(1,5);

$target1=${"box".$nos1};
$target2=${"box".$nos2};
$common=array();
$common=array_intersect($target1,$target2);

答案 1 :(得分:0)

添加到@KamalPaliwal的答案:
使用variable variables完成/编写此代码的另一种方法:

{{1}}