Explanation of PHP foreach array within a function
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 am getting an error that $cars
the statement is foreach
undefined. However, as I understand it, the array $cars
should be global in scope? If I pass the array to the function via the constructor, it works fine. But I am wondering why I cannot access the array this way.
source to share
You have two options.
-
Add a keyword
global
function getCarsByMake($carMake){ global $cars; foreach($cars as $car){ if($car->make == $carMake){ echo 'Car: ' . $car->make . ' ' . $car->model . "<br>"; } } }
-
Use an array
$GLOBALS
:function getCarsByMake($carMake){ foreach($GLOBALS["cars"] as $car){ if($car->make == $carMake){ echo 'Car: ' . $car->make . ' ' . $car->model . "<br>"; } } }
Although I would still recommend passing it as an explicit parameter, as it makes the code more readable and maintainable, IMHO.
source to share
You can call $ cars all over the world, but you can also try in a different way according to your code. Ex:
$car1 = new Car('Ford','Fusion');
$car2 = new Car('Chevy', 'Avalanche');
$car3 = new Car('Ford', 'F150');
$cars = array($car1, $car2, $car3);
function getCarsByMake($carMake,$cars){
foreach($cars as $car){
if($car->make == $carMake){
echo 'Car: ' . $car->make . ' ' . $car->model . "<br>";
}
}
}
getCarsByMake('Ford',$cars);
source to share