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.

+3


source to share


4 answers


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.

+3


source


Along with the Exprator solution, you can also pass an array $cars

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

      

+6


source


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

getCarsByMake('Ford');

      

because the function doesn't get $cars

you need to globally access it inside the function

+3


source


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

      

0


source







All Articles