tags:

views:

267

answers:

6

Thanks for the help here:

http://stackoverflow.com/questions/1744128/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_html/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?

+4  A: 

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

oremj
In php5 objects can be iterated.
Tim Lytle
@Tim Lytle: if that object is the object that should be part of the array that is being looped over, looping over the object and over the array are two different things.
koen
See http://php.net/manual/en/control-structures.foreach.php for more information.
oremj
@koen Yes, but the statement is incorrect and misleading regardless. Since the original question (linked at the top) was using objects, it seems relevant to point out.
Tim Lytle
@Tim Lytle: you are right. It's not about the RealTimeCommissionDataV2 => array in the original post.
koen
how do I wrap it in an array?
pg
To wrap a variable in an array you just need: array($var);
oremj
+2  A: 

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.

koen
How do I cast it to an array?
pg
@pg something like: `foreach ( (array) $yourArray as $key => $val)`
richsage
+2  A: 

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).

Tim Lytle
+1  A: 

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";
}
Banjer
A: 

An example:

<?php

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

?>
Lucas Renan
A: 

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 />";
}
PaulC