Last Updated: February 25, 2016
·
857
· applebiz89

Returning an array in a function: php5.4

If you have a function that returns an array you can easily access the element you want on calling the function. Take for example:

function exampleArray () {
    return array ( 'title' => 'banana', 'body' => 'skin' );
}

If you wanted to just get title from the array within one line you can just do:

$title = exampleArray()['title'];

I thought it was pretty cool and easy.

1 Response
Add your response

The hack for this in PHP versions before this is available is the following

function exampleArray () {
    return array ( 'title' => 'banana', 'body' => 'skin' );
}

list ($title, $body) = array_values(exampleArray());

I say hack because it assumes that the order of values returned from the method will never change which is quite dangerous

over 1 year ago ·