array_pop() や end() を使うと配列の最後尾の値を取得できる。
ただし、関数の戻り値を使うことは許されないらしい。どちらも配列を参照して配列自体をいじるため、実体が必要だから
https://www.php.net/manual/ja/function.end.php
https://www.php.net/manual/ja/function.array-pop.php
問題なく動く
<? $list = [0,1,2]; $v = end($list); print "last is $v\n";
last is 2
ギリ動く
<? $text = "0,1,2"; $v = end(explode(",", $text)); print "last is $v\n";
PHP Notice: Only variables should be passed by reference in /tmp/hoge.php on line 4 last is 2
文句は言うが一応動く。 @でも付ければ隠蔽できる
動かない
<? $v = end([0,1,2]); print "last is $v\n";
PHP Fatal error: Only variables can be passed by reference in /tmp/hoge.php on line 3
同じエラーだけど Notice から Fatal に変わってる。
非破壊版
<? $list = [0,1,2]; $v = array_slice($list,-1)[0]; print "last is $v\n";
last is 2
これなら何も壊さない。 優しい世界
- https://www.drupal.org/project/fileviewer/issues/2505065
- php - Exception 'Only variables should be passed by reference - Stack Overflow
- php - Pop an element from exploded string and convert remaining array to string - Stack Overflow
- PHPで「Only variables should be passed by reference....」エラー - Qiita
- explodeとarray_popは同時に使えない | HABATAKIブログ@翔