Ryan Hipkiss Ryan Hipkiss - 1 month ago 8
PHP Question

Loop over one array as if it was a multidimensional array

I have an array like:

$array = array(
'name' => 'Humphrey',
'email' => 'humphrey@wilkins.com
);


This is retrieved through a function that gets from the database. If there is more than one result retrieved, it looks like:

$array = array(
[0] => array(
'name' => 'Humphrey1',
'email' => 'humphrey1@wilkins.com'
),
[1] => array(
'name' => 'Humphrey2',
'email' => 'humphrey2@wilkins.com'
)
);


If the second is returned, I can do a simple
foreach($array as $key => $person)
, but if there is only one result returned (the first example), I can't run a foreach on this as I need to access like:
$person['name']
within the foreach loop.

Is there any way to make the one result believe its a multidimensional array?

Answer

Try this :

if(!is_array($array[0])) {
    $new_array[] = $array;
    $array = $new_array;
}
Comments