7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHPのforeach文で最初と最後を判別したい処理したくて、resetとendを使ってみたが・・・

Last updated at Posted at 2020-03-17

PHPのforeach文で最初と最後を判別したかったので、備忘録の為に記載。


$array = ['sibuya', 'ebisu', 'meguro', 'gotanda', 'osaki'];
foreach ($array as $key => $value) {
    if ($value === reset($array)) {
        print "${value}は最初だよ\n";
    }
    if ($value === end($array)) {
        print "${value}最後だよ\n";
    }
}

結果

sibuyaは最初だよ
osaki最後だよ

配列要素の最初 sibuya を2つ用意したらどうなる?


$array = ['sibuya', 'ebisu', 'sibuya', 'gotanda', 'osaki'];
foreach ($array as $key => $value) {
    if ($value === reset($array)) {
        print "${value}は最初だよ\n";
    }
    if ($value === end($array)) {
        print "${value}最後だよ\n";
    }
}

結果

sibuyaは最初だよ
sibuyaは最初だよ
osaki最後だよ

おいおい!笑
配列要素内に重複する値が入ってると予期せぬ動きが・・・
待てよ・・・最後の要素も・・・

配列要素の最後 osaki を2つ用意したらどうなる?


$array = ['sibuya', 'ebisu', 'osaki', 'gotanda', 'osaki'];
foreach ($array as $key => $value) {
    if ($value === reset($array)) {
        print "${value}は最初だよ\n";
    }
    if ($value === end($array)) {
        print "${value}最後だよ\n";
    }
}

結果

sibuyaは最初だよ
osaki最後だよ
osaki最後だよ

ジーザス・・・

ループ内で resetend を使うのはご法度らしいですね。
https://qiita.com/ay123/items/90d0e107813e00f2b11f

7
2
5

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
7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?