简体   繁体   中英

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.

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';
});
foreach($aCars as $currentItem)
{
      if(strcmp(substr($currentItem, 0, 1),"F")==0)
      {
      //Do what you need here
      }

}
$aCars = ["BMW", "Audi", "Opel", "Mercedes", "Ford", "Fiat"];
foreach ($aCars as $model) {
    if ($model[0] == "F") {
        echo $model . " ";
    }
}

Probably not the most efficient but short and simple. Match at the beginning of the string ^ the letter F . The / are delimiters for the pattern that can be most any non-alphanumeric, non-backslash, non-whitespace character:

$result = preg_grep('/^F/', $aCars);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM