2

次のコードは、配列に格納されているすべての値を示していますが、ターゲット出力には、文字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>";
  }
?>
4

2 に答える 2

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>";
                }

            }
    ?>
于 2013-02-13T15:30:07.840 に答える
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>";
    }   
  }
?>
于 2013-02-13T15:35:44.777 に答える