开发者

Basic foreach loop question

Thanks for the help here:

foreach loops & stdclass objects

I set up a foreach loop, but the problem is that sometimes the result is:

Warning: Invalid argument supplied for foreach() in /home/MYACCOUNT/public_h开发者_运维百科tml/the script.php on line 81

I think that's when there is nothing to fill the foreach loop but got scared that this was happening when there was indeed one entry.

My question is: what does a foreach loop do when there is only one entry?


foreach only works on arrays, so you'll need to wrap that one element in an array.

As of PHP 5, it is possible to iterate objects too. http://php.net/manual/en/control-structures.foreach.php

To learn more about iterating over objects see: http://www.php.net/manual/en/language.oop5.iterations.php


foreach in PHP5 can iterate over an object, or an Array.

I post this to balance those telling you that you can't use an object.

And as the other answers cover, if your data will be iterated in a foreach, it must be wrapped the same every time. Always an array (even if it's only one element), or always an object (even if it's only one method).


Like oremj says you will need an array. If you sometimes have an array and sometimes only one thing you can cast it to an array to make sure you're working with arrays every time. The one thing will be array('the one thing') after casting it to an array. Then you can loop over it and the loop will start and end with 'the one thing'.

edit: as others have pointed out looping over an object is possible also.


foreach will work just fine on an array containing only 1 element. Try this example:

$foodlist = array("burrito");

foreach ($foodlist as $food) {
  echo $food . "\n";
}


An example:

<?php

$array = array(1, 2, 3, 4, 5);
foreach ($array as $value) {
    echo $value."<br />";
}

?>


Try this:

// Make sure array is an array
if (!$array) $array = array();
if (!is_array($array)) $array = array($array);

foreach ($array as $value) {
    echo $value."<br />";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜