Map array on function return - PHP

Asked

Viewed 150 times

1

Testing local (xampp), with the return of the function mapping an array. Example:

<?php $res = $obj->Function()[0]['name']; ?>

And on the production server (typical hosts) this interpolated form presents a type error "Parse Error";

PHP Parse error: syntax error, Unexpected '[' in path/Archive.php on line 10

How to enable the availability to work with this syntax?

2 answers

1


This resource you want is called array Dereferencing, and is available in PHP 5.4 up. According to PHP documentation:

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.

This means, something you used to do in PHP 5.3 down:

$array = ['a', 'b', 'c'];
echo $array[0]; // a

... can be simplified in PHP 5.4 up:

echo ['a', 'b', 'c'][0]; // 1
  • I didn’t know the term Array "Dereferencing". Using it (including here in the OS) you can find enough content about it.

0

Try this

<?php $res = $obj->Function();
 echo $res[0]['name'];
?>

you will take the return and instantiate in your variable $res then you can manipulate as you please

  • Yes, that’s what I used to make it work. Thanks for the tip. But I figured the answer was something with php.ini, or some apache configuration, or something like that.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.