0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHP の 定数 では end を使えない

Posted at

結論

定数として定義している配列から最後の要素のキーや値を取得したい場合は、array_key_last を使いましょう。

再現

定数の配列に end は使えない
class Test {
  const NUMBERS = [10,20,30];
  function __construct()
  {
    // 期待値は 30
    echo end(self::NUMBERS);
  }
}

はい、無理です

Error - end(): Argument #1 ($array) cannot be passed
by reference in Test.php on line xxx

なぜ?

end関数の引数は参照渡しで受け取る仕組みのため。
https://www.php.net/manual/ja/function.end.php

Stack Overflow の質問コーナー

https://stackoverflow.com/a/49225170
end($s = Self::NUMBERS) のように1回変数に入れればいけるよ、と。

PHP 8.0 では end($s = Self::NUMBERS) でもダメでした

Stack Overflow の参考ページは 6年前のものですし、今は使えないのかも。
全バージョンは試していませんが、
少なくとも PHP 8.0 では前述のトリックは使えませんでした。

正解はコレ
class Test {
  const NUMBERS = [10,20,30];
  function __construct()
  {
    $last_key = array_key_last(self::NUMBERS);
    echo self::NUMBERS[$last_key];
  }
}

これで無事に「30」が返ってきます。

array_key_last は内部ポインタにも影響しないし、
配列の最後の要素を end で取得した場合は reset した方が良く、

どの道 2行にはなるので、array_key_last を使う方が無難ですね。

0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?