PHP 中的字符串真的是字符数组还是其他什么?
考虑
$foo = "abcdefg";
echo $foo[0]; //outputs a
一下,看起来字符串就像字符数组,但为什么
foreach($foo as $char)
{
echo $char;
}
不起作用并给出以下警告?
Warning: Invalid argument supplied for foreach()
Consider
$foo = "abcdefg";
echo $foo[0]; //outputs a
So it seems like strings are like array of characters but then why
foreach($foo as $char)
{
echo $char;
}
does not work and gives following Warning ??
Warning: Invalid argument supplied for foreach()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
讨论了向
foreach
添加字符串迭代支持,但是拒绝了。做出这个决定主要有两个原因:为了解决这两个问题,有人建议引入一个 TextIterator,您可以向其中传递一个字符串和一个字符集。这样您就不会意外地迭代字符串,并且不存在字节与字符问题。我不确定 TextIterator 当前的状态是什么。
Adding string iteration support to
foreach
was discussed but declined. There were mainly two reasons for this decision:To solve both problems there was a proposal to introduce a
TextIterator
, which you pass a string and a charset. That way you can't accidentally iterate a string and the byte vs character problem doesn't exist. I'm not sure though what the state of theTextIterator
is currently.NikiC 的回答涵盖了为什么直接这样做是不可能的。
如果您想像数组一样迭代字符串,可以使用
str_split
:警告:
str_split
不支持编码,因此您最终将迭代 字节且未超过字符。迭代字符有点复杂,因为没有等效的多字节分割函数。您可以使用启用正则表达式的mb_split
,查看来自 PHP.net 的评论< /a> 寻求想法。这里还有其他答案建议您应该将字符串转换为数组,但我不明白为什么这会起作用。 文档非常明确:
事实上,这样做并不像建议的那样工作。
NikiC's answer covers why doing this directly is not possible.
If you want to iterate over a string as if it were an array, you can be explicit by using
str_split
:Warning:
str_split
is not encoding-aware, so you will end up iterating over bytes and not over characters. Iterating over characters is a little more involved, as there is no equivalent multibyte split function. You can roll your own using the regex-enabledmb_split
, look at the comments from PHP.net for ideas.There are other answers here suggesting you should cast the string to an array, but I don't understand why that would work. The documentation is pretty explicit:
And indeed, doing this does not work as suggested.
尽管可以使用方括号来寻址它们的字符,字符串不是数组< /a>.强调我的:
Even though their characters can be addressed using square brackets, strings aren't arrays. Emphasis mine:
它被称为“语法糖”。
例如,在 5.4 中,您将能够执行以下操作
echo func()[0];
这并不意味着函数实际上是一个字符数组。
这只是一个语法。
it is called "syntax sugar".
For example, in 5.4 you'll be able to do like this
echo func()[0];
That doesn't mean that a function is really an array of charactes.
It's just a syntax.