How to return an array and get the first element of it in one line in PHP?

后端 未结 4 1718
轮回少年
轮回少年 2021-01-22 16:58

this question is just for fun and maybe learning a PHP shorthand trick (if exists) Let\'s assume that I have this code:

$item = $this->get_item($id);
$item =          


        
4条回答
  •  长情又很酷
    2021-01-22 17:41

    In PHP 5.4 this becomes an easy one-liner

    As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.

    $firstElement = getArray()[0];
    

    where

    function getArray() {
        return array(1, 2, 3);
    }
    

    Taken from a slightly modified version of Example #7 from the PHP manual pages (Arrays).

提交回复
热议问题