Search code examples
phparraysloopsvariableselement

How can I show an array element that starts with a specific letter in PHP


this is my array:

$aCars = array("BMW", "Audi", "Opel", "Mercedes", "Ford", "Fiat");

And I want to show only the array elements which start with the letter F.

But what is the most efficient method to do this, I have seen more questions like this, but I want to have a most efficient method to do this.


Solution

  • array_filter() will probably be faster, since it is machine code, not interpreted PHP code.

    $filteredCars = array_filter($aCars, function($car) {
        return $car[0] == 'F';
    });
    

    Using an arrow function:

    $filteredCars = array_filter($aCars, fn($car) => $car[0] === "F");