Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get items in multidimensional array separately

Tags:

arrays

php

I have an array ($myArray) like this:

print_r(array_values ($myArray));

result: Array ( 
    [0] => 
    [1] => Array ( 
        [id] => 1 
        [name] => ABC 
    ) 
    [2] => Array ( 
        [id] => 2 
        [name] => DEF 
    ) 
)

I'm trying to get each ID and NAME.. So Im trying this:

foreach ($myArray as $value) {
    foreach($value as $result) {
        echo $result;
    }
}

I'm facing two problems:

  1. I get a PHP WARNING that says: " Invalid argument supplied for foreach() on line 29

This line is: foreach($value as $result) {

  1. I would like to get keys to ID and NAME to place them in correct places. This ways echo "1ABC" and "2DEF"

Any idea? Thanks for helping.

like image 905
user3787036 Avatar asked Jul 12 '26 03:07

user3787036


1 Answers

Basically, the error triggered, since the array in your example (index zero in particular) is not an array (most likely an empty string/null ) which is being used inside foreach.

Since one of the elements is not an array, you could just check that if its an array or not using is_array():

foreach($myArray as $values) {
    if(is_array($values)) {
        echo $values['id'] . ' ' . $values['name'] . '<br/>';
    }
}

Alternatively, you could also use array_filter() in this case which in turn removes that empty index zero, so that you could just use that loop that you have. You wouldn't have to check for that empty element.

$myArray = array_filter($myArray);
foreach ($myArray as $value) {
    foreach($value as $result) {
        echo $result;
    }
}
like image 74
Kevin Avatar answered Jul 14 '26 18:07

Kevin