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
3 Answers
$item = $obj; // or $item = array( ... ); if(!is_array($item)) $item = array($item); foreach($item as $individual) { //... } 1 Comment
user229044
Extremely common pattern in PHP, I find
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
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
pHelics
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.