显示特定字母的数组值

时间:2013-02-13 15:19:32

标签: php loops

以下代码显示存储在数组中的所有值,但我的目标输出仅显示以字母T开头的值。

有人可以帮我转换此代码,只提取以字母T开头的值吗?

<?php
$cars=array("Volvo1","Volvo2","Volvo3","Volvo4","Volvo5","Volvo6",
            "BMW1","BMW2","BMW3","BMW4","BMW5","BMW"6,
            "Toyota1","Toyota2","Toyota3","Toyota4","Toyota5","Toyota6");
$arrlength=count($cars);

for($x = 0;$x < $arrlength; $x++)
  {
  echo $cars[$x];
  echo "<br>";
  }
?>

2 个答案:

答案 0 :(得分:2)

你可以试试这样的东西吗?

<?php
       $cars=array("Volvo1","Volvo2","Volvo3","Volvo4","Volvo5","Volvo6","BMW1","BMW2","BMW3","BMW4","BMW5","BMW", "Toyota1","Toyota2","Toyota3","Toyota4","Toyota5","Toyota6");
       $arrlength=count($cars);

       for($x = 0;$x < $arrlength; $x++)
       {
            // substr(string, start, length)
            if(substr($cars[$x], 0, 1) === 'T')
            {
               echo $cars[$x];
               echo "<br>";
            }

            // or use this
            // 0 is first character of the string
            if($cars[$x][0] === 'T')
            {
               echo $cars[$x];
               echo "<br>";
            }

        }
?>

但更好的方法是使用for循环而不是使用foreach循环,如下所示,

<?php
           $cars=array("Volvo1","Volvo2","Volvo3","Volvo4","Volvo5","Volvo6","BMW1","BMW2","BMW3","BMW4","BMW5","BMW", "Toyota1","Toyota2","Toyota3","Toyota4","Toyota5","Toyota6");

           foreach($cars as $car)
           {
                // substr(string, start, length)
                if(substr($car, 0, 1) === 'T')
                {
                   echo $car;
                   echo "<br>";
                }

                // or use this
                // 0 is first character of the string
                if($car[0] === 'T')
                {
                   echo $car;
                   echo "<br>";
                }

            }
    ?>

答案 1 :(得分:1)

<?php
$cars=array("Volvo1","Volvo2","Volvo3","Volvo4","Volvo5","Volvo6",
            "BMW1","BMW2","BMW3","BMW4","BMW5","BMW6",
            "Toyota1","Toyota2","Toyota3","Toyota4","Toyota5","Toyota6");
$arrlength=count($cars);

$key = "T"; //Or what you want
for($x = 0;$x < $arrlength; $x++)
  {
    if($cars[$x][0]==$key) 
    {
        echo $cars[$x];
        echo "<br>";
    }   
  }
?>