I have a rather big php script that uses the foreach loop pretty often. The way it works now is I pass an array of objects to every foreach loop, but I want to modify the script to work with just an object also. I would really hate and don't think it's reasonable to check before each loop if it's an array of objects or just a single object and depending on the situation to loop through the array or just do stuff with the single object. Any workaround this? Thanks in advance
PHP provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement. By default, all visible properties will be used for the iteration.
Note − If there are more than 2 arrays, nested 'foreach' loops can be used. Here, 2 arrays have been declared and they are being traversed using the 'foreach' loop. The result is that the respective index of every array is matched and the data at those indices are displayed one next to the other.
$item = $obj;
// or
$item = array( ... );
if(!is_array($item))
$item = array($item);
foreach($item as $individual)
{
//...
}
You can pass an array with a single object inside it. Or use a polymorphic constructor/function setup.
Passing an array with a single object is pretty obvious how to do it, here's some other possible ways to deal with it:
function test($var)
{
if(is_a($var,"ClassName")) //Test to see if the passed variable is a member of the class and not an array and put it in an array if so
{
$var = array($var);
}
foreach($var as $v)
{
//Do stuff
}
}
function test($var)
{
if(is_array($var)) //Test if object is array or class, call different functions depending on which it is
{
call_user_func_array(array($this,'doArray'),$var);
}
elseif(is_a($var,"Classname"))
{
call_user_func_array(array($this,'doObject'),$var);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With