2013-02-13 73 views
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>"; 
    } 
?> 

回答

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
<?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>"; 
    } 
    } 
?> 
相關問題