Oliver Nassar

php's foreach on a string? you can do that.

July 22, 2009

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.";
}