• posted 2½ years ago
  • 5 comments

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

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

Comments (add comment)

 
  • Oliver Nassar

    Oliver Nassar 1 year ago

    Here's what's weird: this page is the single biggest source of search engine traffic. My logs show this one always being hit. Can anyone who see's this let me know what you need help with and I'll try and write a more relevant post?

    Thanks.
    Oliver
    • Guido Schlabitz

      Guido Schlabitz 1 year ago

      Hi,

      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

      Oliver Nassar 10 months ago

      @guido
      hmmm, strange. I tested again, and the following works on php 5.3.3
      $unknown = array('oliver', 'nassar');
      foreach((array) $unknown as $key => $value) {
          echo "go nuts.";
      }
      $unknown = 'kittens';
      foreach((array) $unknown as $key => $value) {
          echo "go nuts.";
      }
      Feel free to try that and see if it works.
  • Dane

    Dane 10 months ago

    I think its here because it answers exactly the question I have.

    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

      Oliver Nassar 10 months ago

      thanks dude. I updated it a few mins ago because I realized some of the grammer didn't make sense, lol. and added email notifications for replies (haha, let's see if that's true and you're reading this right now).

      anyway, thanks for the kudos. glad I can help :)