This question already has an answer here:
I have following array:
<?php
$cars = array(
"cars" => array
(
array("make" => "Volvo", "model" => "2018", "price" => 31.91),
array("make" => "BMW", "model" => "2015", "price" => 34.50),
array("make" => "Toyota", "model" => "2019", "price" => 27.58)
)
);
echo "<pre>";
print_r($cars);
echo "</pre>";
?>
Human readable form:
Array
(
[cars] => Array
(
[0] => Array
(
[make] => Volvo
[model] => 2018
[price] => 31.91
)
[1] => Array
(
[make] => BMW
[model] => 2015
[price] => 34.5
)
[2] => Array
(
[make] => Toyota
[model] => 2019
[price] => 27.58
)
)
)
How can we traverse this array to get every elements? Is it necessary to use OUTER foreach
loop to get access inside cars
array? Can we not access them directly if we already knew about the key in advance?
I am using following approach:
<?php
foreach($cars as $key => $array)
{
echo "Key: " . $key;
echo "<hr />";
foreach($array as $sub_key => $sub_array)
{
echo "Make:" . $sub_array['make'];
echo "<br />";
echo "Model:" . $sub_array['model'];
echo "<br />";
echo "Price:" . $sub_array['price'];
echo "<hr />";
}
}
?>
Output:
Key: cars
Make:Volvo
Model:2018
Price:31.91
Make:BMW
Model:2015
Price:34.5
Make:Toyota
Model:2019
Price:27.58
How to traverse array elements without using outer foreach
loop? I mean without using
foreach($cars as $key => $array)
EDIT
I don't think it is duplicate to those questions in any means. My question is to avoid the need of outer loop and not the inner loop.
</div>