Get elements in multidimensional array separately
I have an array ($ myArray), for example:
print_r(array_values ($myArray));
result: Array (
[0] =>
[1] => Array (
[id] => 1
[name] => ABC
)
[2] => Array (
[id] => 2
[name] => DEF
)
)
I am trying to get each ID and NAME .. So what I am trying to do is:
foreach ($myArray as $value) {
foreach($value as $result) {
echo $result;
}
}
I have two problems:
- I am getting a PHP WARNING saying "Invalid argument provided for foreach () on line 29
This line is: foreach($value as $result) {
- I would like to get the keys for the ID and NAME so I can place them in the correct places. This allows echoing "1ABC" and "2DEF"
Any idea? Thanks for the help.
source to share
Basically, the error is triggered because the array in your example (in particular the index zero) is not the array (most likely an empty string / null) that is used internally by the foreach.
Since one of the elements is not an array, you can simply check that if its an array or not use is_array()
:
foreach($myArray as $values) {
if(is_array($values)) {
echo $values['id'] . ' ' . $values['name'] . '<br/>';
}
}
Alternatively you can also use array_filter()
in this case, which in turn removes the zero zero index so you can just use that loop you have. You won't need to check for this empty element.
$myArray = array_filter($myArray);
foreach ($myArray as $value) {
foreach($value as $result) {
echo $result;
}
}
source to share