【问题标题】:How can I show an array element that starts with a specific letter in PHP如何在 PHP 中显示以特定字母开头的数组元素
【发布时间】:2019-02-14 15:20:55
【问题描述】:

这是我的数组:

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

我只想显示以字母 F 开头的数组元素。

但是什么是最有效的方法来做到这一点,我见过更多这样的问题,但我想有一个最有效的方法来做到这一点。

【问题讨论】:

  • Foreach 并测试第一个字符

标签: php arrays loops variables element


【解决方案1】:

array_filter()可能会更快,因为它是机器代码,而不是解释的 PHP 代码。

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

【讨论】:

    【解决方案2】:
    foreach($aCars as $currentItem)
    {
          if(strcmp(substr($currentItem, 0, 1),"F")==0)
          {
          //Do what you need here
          }
    
    }
    

    【讨论】:

      【解决方案3】:
      $aCars = ["BMW", "Audi", "Opel", "Mercedes", "Ford", "Fiat"];
      foreach ($aCars as $model) {
          if ($model[0] == "F") {
              echo $model . " ";
          }
      }
      

      【讨论】:

        【解决方案4】:

        可能不是最有效的,但简短而简单。匹配字符串^ 开头的字母F/ 是模式的分隔符,几乎可以是任何非字母数字、非反斜杠、非空白字符:

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

        【讨论】:

        • (太好了,没见过。)
        猜你喜欢
        • 2018-07-24
        • 2020-10-05
        • 1970-01-01
        • 1970-01-01
        • 2018-03-15
        • 1970-01-01
        • 1970-01-01
        • 2014-11-03
        • 1970-01-01
        相关资源
        最近更新 更多