LoginSignup
25
22

More than 5 years have passed since last update.

[php]foreachで最後だけ例外処理

Last updated at Posted at 2015-06-20

基本だが、良く忘れるのでメモ。
end()を使う。

例)最後だけ改行を出力しない

index.php
$h = [];
$h['a'] = 'testa';
$h['b'] = 'testb';
$h['c'] = "testc";

foreach($h as $key => $value){
    echo $key.' '.$value.'\n';

    if($value !== end($h)){
        echo "\n";
    }
}
/* 実行結果
a testa
b testb
c testc
*/

[追記]
@mpyw,@ngyukiさんから、下にもありますがご指摘いただきました。

end()や、reset()は、本来このようには使われないそうです。(・△・)ホォ..
という訳でcountで作り直してみました。

index.php
$h = [];
$h['a'] = 'testa';
$h['b'] = 'testb';
$h['c'] = "testc";

$length = count($h);     // 追加
$no = 0;    // 追加

foreach($h as $key => $value){

    echo $key.' '.$value.'\n';
    $no++; // 追加

    if($no !== $length){    // 変更
        echo "\n";
    }
}

/* 実行結果
a testa
b testb
c testc
*/

@mpyw @ngyukiさん、ご指摘ありがとうございました!

25
22
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
22