Skip to content
Advertisement

How to handle passing an array or single value to a function

I want to make a function that accepts an array or single value as a parameter (I want foreach() to work in two cases)

function handle($users)
{
   foreach($users as $user){}    
}

So what I’m really want to do is to make the above function works if I pass handle($users) as an array of objects or handle($user) as a single object

Advertisement

Answer

Test $users before you use it

function handle($users)
{
    if (is_array($users)) {
        foreach($users as $user){}    
    }else{
        // its a single object
    }
}

or pass the single user in an array anyway.

function handle($users)
{
   foreach($users as $user){}    
}

handle([$user]);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement