万一如何使用数组?
在有开关的情况下如何使用数组?这不起作用,并且始终采用默认值 (3):
switch ($my_array) {
case array('george','paul'):
$id = 1;
break;
case array('paul','max'):
$id = 2;
break;
case array('eric'):
$id = 3;
break;
//default
default:
$id = 3;
break;
}
How can I use an array in the case of a switch? This doesn't work and always take the default (3):
switch ($my_array) {
case array('george','paul'):
$id = 1;
break;
case array('paul','max'):
$id = 2;
break;
case array('eric'):
$id = 3;
break;
//default
default:
$id = 3;
break;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
根据有关数组运算符的 PHP 手册,您的示例应该可以工作:
由于 switch/case 使用弱比较,因此使用
==
运算符来比较数组。我在键盘上放置了一个工作示例: http://codepad.org/MhkGpPRp
Your example should work, according to the PHP manual on array operators:
Since switch/case uses weak comparison, arrays are compared by using the
==
operator.I've put a working example onto codepad: http://codepad.org/MhkGpPRp
PHP 可以打开数组,但您确实需要所有元素具有完全相同的键才能成功进行比较。您可能需要使用 array_values() 来规范化键$我的_数组。否则它应该有效。
$my_array = array('paul','max');
应该给出 $id=2。PHP can switch on arrays, though you do need to have exactly the same keys of all the elements for the comparison to succeed. You might need to use array_values() to normalize the keys of $my_array. Otherwise it should work.
$my_array = array('paul','max');
should give $id=2.你可以尝试使用这样的:
但你真的想要它吗?
You can try to use some like this:
But you really want it?
switch()
语句旨在匹配单个条件。我不认为有办法使用开关来实现这一点。您需要使用if else
链:根据 数组运算符规则,可以使用
==
,但数组成员的顺序必须相同。从技术上讲,只有键和值必须匹配,但对于数字索引数组,这相当于成员具有相同的数字顺序。switch()
statements are intended to match single conditions. I don't think there will be a way to use a switch for this. You need to use anif else
chain instead:According to array operator rules, you can use
==
, but the array members must be in the same order. Technically, it is only the keys and values that must match, but for a numeric-indexed array, this equates to the members being in the same numeric order.