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
:
foreach(str_split($foo) as $char)
{
echo $char;
}
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-enabled mb_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:
For any of the types: integer, float, string, boolean and resource,
converting a value to an array results in an array with a single
element with index zero and the value of the scalar which was
converted. In other words, (array)$scalarValue is exactly the same as
array($scalarValue).
And indeed, doing this does not work as suggested.