
Reminder to self:
Normally, to do a foreach, the array must be something like:
array("oliver", "nassar")I've run into a situation where I didn't know if a variable (lets say $unknown) was an array or just a string. Running foreach on a string results in the warning:Warning: Invalid argument supplied for foreach() in /random/file/path.php on line #line-number
Just write this, and you should be good:
foreach((array) $unknown as $key => $value) {
echo "go nuts.";
}
Comments (add comment)
Oliver Nassar 1 year ago
Thanks.
Oliver
Guido Schlabitz 1 year ago
I got here, because I googled "php foreach string" and you're number 3 in the results, right after php.net.
Your solution did not work for me (at least not in PHP5), so I went with the old
for ($i=0; $i < strlen($str); $i++)
instead. To make your example work, you would have to str_split the string first, but that defeats the purpose of this short cut.Oliver Nassar 10 months ago
hmmm, strange. I tested again, and the following works on php 5.3.3
$unknown = array('oliver', 'nassar');
Feel free to try that and see if it works.foreach((array) $unknown as $key => $value) {
echo "go nuts.";
}
$unknown = 'kittens';
foreach((array) $unknown as $key => $value) {
echo "go nuts.";
}
Dane 10 months ago
There are numerous cases you'd want to perform an operation on a string and loop it if its passed an array of strings. This is the simplest and most understandable way of implementing that without causing an error if a string is passed to it.
Oliver Nassar 10 months ago
anyway, thanks for the kudos. glad I can help :)