foreach() 适用于非数字数组键吗?
我想知道当数组如下所示时 foreach() 是否有效:
- arr_name[eggs] = some
- arr_name[pencil] = some else
如果运行为 foreach 是否会工作:
foreach(arr_name as $key => $value)
因为它们具有非数字值的键?
I was wondering if foreach() works when the array looks like this:
- arr_name[eggs] = something
- arr_name[pencil] = something else
Will foreach work if run as:
foreach(arr_name as $key => $value)
for they keys that have a non-numerical value ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,
foreach
支持任何类型的键。在您的情况下,$key
将是一个字符串,每个项目分别为'eggs'
和'pencil'
。事实上,foreach
旨在与具有非数字键的数组一起使用,您无法使用for
轻松迭代这些数组。Yes,
foreach
supports any kind of key. In your case,$key
will be a string,'eggs'
and'pencil'
respectively for each item. In fact,foreach
was intended for use with arrays that have non-numerical keys which you can't easily iterate usingfor
.是的,PHP 在具有数字键和非数字键的数组之间没有真正的区别。就 PHP 而言,它们都是简单的数组。
Yes, PHP has no real distinction between arrays with numeric vs non-numeric keys. They're all simply arrays as far as PHP is concerned.
是的,BoltClock 给出的解释是正确的&我建议你也手动尝试一下。您在 foreach 语句中错过了 $before 数组名称
foreach($arr_name as $key=>$value)
回显$值
?>
Yes the explanation given by BoltClock is right & i would suggest you to manually try too. You have missed $before array name in the foreach statement
foreach($arr_name as $key=>$value)
echo $value
?>