Reed
Reed

Reputation: 1642

Explanation of PHP array foreach scope within 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 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.

Upvotes: 4

Views: 1943

Answers (4)

rowmoin
rowmoin

Reputation: 708

You can call $cars globally but you can also try by another 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);

Upvotes: 0

Marvin
Marvin

Reputation: 14425

You have two options.

  1. Add the global keyword

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

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

Although I'd still recommend passing it as an explicit parameter as that makes the code more readable and maintainable, IMHO.

Upvotes: 3

GrumpyCrouton
GrumpyCrouton

Reputation: 8621

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);

Upvotes: 6

Exprator
Exprator

Reputation: 27523

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

getCarsByMake('Ford');

its because the function is not getting the $cars , you need to globally access it inside the function

Upvotes: 3

Related Questions