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.
Written by Ashley Banks
Related protips
1 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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Related Tags
#php
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#