[英]better solution?
This script picks element inside of the array and print it. 该脚本在数组内部拾取元素并进行打印。
<?php
$word = array("THE", "QUICK", "BROWN", "FOX", "JUMPS");
$rand_keys = array_rand($word, 2);
echo $word[$rand_keys[0]];
echo $word[$rand_keys[1]];
?>
it works but i'm using some function 它有效,但是我正在使用某些功能
array_diff();
array_diff();
which on my script search from the $word
variable and removes from the element list example: 该脚本在我的脚本中从
$word
变量中搜索,并从元素列表示例中删除:
$word = array("THE", "QUICK", "BROWN", "FOX", "JUMPS");
$ word = array(“ THE”,“ QUICK”,“ BROWN”,“ FOX”,“ JUMPS”);
$sentence = array("QUICK", "BROWN");
$ sentence = array(“ QUICK”,“ BROWN”);
$input = array_diff($word, $sentence);
$ input = array_diff($ word,$ sentence);
so $input
is containing array("THE", "FOX", "JUMPS");
因此
$input
包含array("THE", "FOX", "JUMPS");
right? 对?
and I apply to the script like to this: 我将脚本应用于此:
<?php
$word = array("THE", "QUICK", "BROWN", "FOX", "JUMPS");
$sentence = array("QUICK", "BROWN");
$input = array_diff($word, $sentence);
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]];
echo $input[$rand_keys[1]];
?>
it also works because it contains 3 elements on the array. 它也起作用,因为它在数组上包含3个元素。 If I do more filtering and the
如果我进行更多过滤 ,
$input
$输入
variable contains only 1 element ex: $input
only contains array("BROWN");
变量仅包含1个元素,例如:
$input
仅包含array("BROWN");
the script won't run anymore and getting errors like: 该脚本将不再运行,并出现以下错误:
Warning: array_rand(): Second argument has to be between 1 and the number of elements in the array in
警告:array_rand():第二个参数必须在1和数组中元素的数量之间
Notice: Undefined index: in
注意:未定义的索引:in
Notice: Undefined index: in
注意:未定义的索引:in
how can I run the script if the array element containing only 1 ? 如果数组元素仅包含1,如何运行脚本?
I've come this far it works but is there any better solution? 我已经走了这么远,但是还有更好的解决方案吗?
<?php
$word = array("THE", "QUICK", "BROWN", "FOX", "JUMPS");
if(count($input) >= 2)
{
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
}
else
{
echo end($input);
}
?>
Error message is simple and easy to understand. 错误消息简单易懂。 You can't use number bigger than count of elements in second argument of
array_rand()
. 您不能在
array_rand()
第二个参数中使用大于元素数的数字。
Before calling this function check what is count of elements and in case it's only one, use this element without calling array_rand()
. 在调用此函数之前,请检查什么是元素计数,如果只有一个,请在不调用
array_rand()
情况下使用此元素。 Also be prepared for situation when you've got no elements at all. 当您根本没有任何要素时,也要为情况做好准备。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.