2017-08-13 8 views
2

foreachループを使用していくつかの追加値を追加します。PHPは最後のforeachループで値を追加します

foreach($a as $b) { 
echo $b; // this will print 1 to 6 
} 

は今、私は私がこれをどのように行うことができます

1 
2 
3 
4 
5 
6 this is last. 

次のようにカスタムテキスト と最後の項目を編集し、印刷したいですか?私がPHPで新しいのを助けてください。

+0

'場合(Bの== 6)'例えば同じようcondicionalに使用することができますthatsの道を数えます。 –

答えて

9

あなたは、配列のendを使用することができます

<?php 
$a = array(1,2,3,4,5,6); 
foreach($a as $b) { 
echo $b; // this will print 1 to 6 
if($b == end($a)) 
    echo "this is last."; 
echo "<br>"; 
} 

EDIT あなたが同じ値を持っている場合あなたがそれを行うことができ、@のアレクサンドルコメントとしてキー

<?php 
$a = array(6,1,2,3,4,5,6); 
end($a);   // move the internal pointer to the end of the array 
$last_key = key($a); 
foreach($a as $key=>$b) { 
echo $b; // this will print 1 to 6 
if($key == $last_key) 
    echo "this is last."; 
echo "<br>"; 
} 
+0

ありがとうございます。未知数の配列でどうすればいいですか? –

+0

'[6,1,2,3,4,5,6]'のような配列ではうまくいきません。 –

+0

@anamahmed 'unknown number of array'はどういう意味ですか? –

3

あなたは、INC変数を宣言することができますし、配列数で使用する

<?php 
//$b is your array 
$i=1; 
foreach($a as $b) { 
if(count($a)==$i){ 
    echo $b; // this is last  
} 
$i++; 
} 
?> 
+0

ありがとう兄弟は働いて素晴らしい... –

+0

あなたは答えをupvoteできますか? –

4
<?php 
$a = array(1,2,3,4,5,6); 
$last = count($a) - 1; 
foreach($a as $k => $b) { 
echo $b; // this will print 1 to 6 
if($k == $last) 
    echo "this is last."; 
echo "<br>"; 
} 
+0

ありがとうございました。 –

1

使用、あなたのサイズを取得し、あなたがもし

$size=count($a); 

foreach($a as $b) { 

     if ($b==$size) 
     { 
      echo $b. "This is the last"; // this will print 6 and text 
     } 
    else 
    { 
     echo $b; // this will print 1 to 5 
    } 
} 
関連する問題