5

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

1
  • I'd say if at multiple points in your script you're not sure whether you're working on a single object or an array of objects you have a problem defining your data flow correctly. Commented Mar 2, 2011 at 1:13

3 Answers 3

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

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

foreach($item as $individual)
{
   //...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Extremely common pattern in PHP, I find
1

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);
    }
}

Comments

0

Sounds like you need to write a function/Would this serve your purposes?

if(is_array($thingy)){
    foreach($thingy as $thing){
        function($thing);
    }
}else{
    function($thingy);
}

1 Comment

That was what I was trying to avoid, if have at least a couple dozens foreach loops and adding. I would hate to wrap every foreach loop content in a functions. Thanks anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.