Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP foreach on array of objects AND single object?

Tags:

foreach

php

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

like image 365
pHelics Avatar asked Mar 02 '11 01:03

pHelics


People also ask

Can I use foreach on Object in PHP?

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.

Can we use two foreach loop in PHP?

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.


2 Answers

$item = $obj;
// or
$item = array( ... );

if(!is_array($item))
   $item = array($item);

foreach($item as $individual)
{
   //...
}
like image 115
Tim Cooper Avatar answered Sep 28 '22 06:09

Tim Cooper


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);
    }
}
like image 32
Phoenix Avatar answered Sep 28 '22 07:09

Phoenix