Djordje Petrovic Djordje Petrovic - 1 month ago 6
PHP Question

PHP looping thrue milti array with foreach

i need to loop thru array with foreach and only list cars that are younger then 2000

$cars = array(array("model"=>"Volvo","year"=>2010),array("model"=>"BMW","year"=>1995),array("model"=>"Saab","year"=>1998),array("model"=>"Land Rover","year"=>2004)

Answer
<?php
$cars = array(
    array(
        "model" => "Volvo",
        "year" => 2010
    ) ,
    array(
        "model" => "BMW",
        "year" => 1995
    ) ,
    array(
        "model" => "Saab",
        "year" => 1998
    ) ,
    array(
        "model" => "Land Rover",
        "year" => 2004
    )
);


foreach($cars as $car){
    if($car['year'] > 2000){

//Write code to do what you want to do with the car. Next line just prints it.

        echo $car['model'].'</br>' ;
    }
}

Output:

Volvo
Land Rover

Foreach loop takes each of the car in $car variable which is another array. inside foreach check for the value in model. if is younger than 2000 then do whatever you want to do with that.