1

Got an assignment for school to make a multidimensional array.

<?php
$cars = array( 
        "car1" => array (   
            "brand" => 'BMW',
            "license" => '30-KL-PO',    
            "price" => 10000
            ),

        "car2" => array (
           "brand" => 'Mercedes',
           "license" => '51-ZD-ZD',
           "price" => 20000
        ),

        "car3" => array (
           "brand" => 'Maserati',
           "license" => 'JB-47-02',
           "price" => 30000
        )
     );

foreach($carss as $car){
echo $car['car1']['brand'] . $car['car1']['brand'] . "<br>";
}

?>

I need to show the brand and license of all the cars using a foreach. I tried it with only car1 and I got the error: Undefined index: car1.

I know how to get it to show using only echo but my assignment says that I have to using a foreach.

The Codesee
  • 3,714
  • 5
  • 38
  • 78
Mr J.
  • 215
  • 1
  • 4
  • 12

3 Answers3

7

change your loop as

foreach($carss as $key => $car){
   echo $key ." ". $car['brand'] . "<br>";
}
RAUSHAN KUMAR
  • 5,846
  • 4
  • 34
  • 70
4

You were not far off:

<?php
$cars = array( 
        "car1" => array (   
            "brand" => 'BMW',
            "license" => '30-KL-PO',    
            "price" => 10000
            ),

        "car2" => array (
           "brand" => 'Mercedes',
           "license" => '51-ZD-ZD',
           "price" => 20000
        ),

        "car3" => array (
           "brand" => 'Maserati',
           "license" => 'JB-47-02',
           "price" => 30000
        )
     );

foreach($cars as $car)
    printf("%-10s %s\n",  $car['brand'], $car['license']);

Output:

BMW        30-KL-PO
Mercedes   51-ZD-ZD
Maserati   JB-47-02

To target an individual value from $cars using keys:

echo $cars['car1']['brand'];

Output:

BMW
Progrock
  • 7,373
  • 1
  • 19
  • 25
0

You may do something like this

<?php
$cars = array( 
    "car1" => array (   
        "brand" => 'BMW',
        "license" => '30-KL-PO',    
        "price" => 10000
    ),
    "car2" => array (
        "brand" => 'Mercedes',
        "license" => '51-ZD-ZD',
        "price" => 20000
    ),
    "car3" => array (
        "brand" => 'Maserati',
        "license" => 'JB-47-02',
        "price" => 30000
    )
);
$result = []; // blank array to store result 
foreach($cars as $key => $val):
$result[$key]["brand"] = $val["brand"]; 
$result[$key]["license"] = $val["license"]; 
endforeach;
#echo "<pre>";
#print_r($result);
?>
Aman Kumar
  • 4,533
  • 3
  • 18
  • 40