Prakash Raman
Prakash Raman

Reputation: 13933

How access a key of a array which is returned by a function

I want to be able to access the array directly from the return value of the function.

e.g. 
$arr = find_student();
echo $arr['name'];

// I want to be able to do
echo find_student()['name']

How can I accomplish the same ? Without another line of code ?

Upvotes: 1

Views: 60

Answers (3)

Kristian
Kristian

Reputation: 3461

You can do something similiar using ArrayObject.

function find_student() {
//Generating the array..
$array = array("name" => "John", "age" => "23");

return new ArrayObject($array);
}

echo find_student()->name;
// Equals to
$student = find_student();
echo $student['name'];

Downside is you cant use native array functions like array_merge() on that. But you can access you data as you would on array and like on an object.

Upvotes: 2

Prof
Prof

Reputation: 2908

You cant :)

function find_student() {return array('name'=>123);}
echo find_student()['name'];

Result: Parse error: syntax error, unexpected '[', expecting ',' or ';'

Upvotes: 2

knittl
knittl

Reputation: 265211

You can't. The PHP syntax parser is limited and does not allow it in current versions.

The PHP devs extended the parser for upcoming releases of PHP. Here's a link to a blog talking about it

Upvotes: 6

Related Questions