phparraysfunctionreturn-value

Can a specific element from the array returned from a function be directly accessed?


If myFunction returns an array, is there a simpler way of doing this?

$result = myFunction($parameters);
$result = $result[4];

Solution

  • PHP does not support array dereferencing in this way, i.e. this is invalid:

    $result = myFunction($parameters)[4];
    

    Some options, none of which are particularly elegant or readable:

    list(,,,,$result) = myFunction($parameters); // ignore first 3
    $result = array_pop( array_slice( myFunction($parameters), 4, 1 ) ); // grab 4th element