Press "Enter" to skip to content

Array Dereferencing

First, a word on the title — I adopted the official term from the changelog, since a direct literal rendering doesn't quite capture the meaning.
In PHP 5.4, there is a new improvement:

- Added array dereferencing support. (Felipe)

In the past, if we defined a function that returns an array:

<?php
function foo() {
    return array(1, 2, 3);
}

then, if I wanted to get the second element of the returned array, I could only:

<?php
list(, $mid, ) = foo();

or:

$tmp  =  $foo();
$mid = $tmp[1];

Starting from 5.4, we no longer need to go through that trouble — we just need:

<?php
$mid = foo()[1];

Also, you can use references:

<?php
function &getTable() {
     return $GLOBALS;
}
getTable()["foo"] = "laruence";
echo $foo;
//laruence

Pretty convenient, right? Hehe. Finally, a reminder: PHP 5.4 is still under development. Before the final release, any new feature may be adjusted or changed. If you have any suggestions, feedback is welcome, to help make PHP even better.
Thanks

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.