Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of PHP array foreach scope within function

Tags:

php

I have the following PHP code:

$car1 = new Car('Ford','Fusion');
$car2 = new Car('Chevy', 'Avalanche');
$car3 = new Car('Ford', 'F150');

$cars = array($car1, $car2, $car3);

function getCarsByMake($carMake){
    foreach($cars as $car){
        if($car->make == $carMake){
            echo 'Car: ' . $car->make . ' ' . $car->model . "<br>";
        }
    }
}

getCarsByMake('Ford');

I get the error that $cars in the foreach statement is undefined. However, as I understand it, the $cars array should be global in scope? If I pass the array into the function through the constructor it works fine. But I'm wondering why I can't access the array in this way.

like image 699
Reed Avatar asked Oct 19 '25 13:10

Reed


1 Answers

Along with Exprator's solution, you could also pass the $cars array to the function like this.

function getCarsByMake($carMake, $cars){
    foreach($cars as $car){
        if($car->make == $carMake){
            echo 'Car: ' . $car->make . ' ' . $car->model . "<br>";
        }
    }
}

getCarsByMake('Ford', $cars);
like image 106
GrumpyCrouton Avatar answered Oct 21 '25 04:10

GrumpyCrouton