Web Development

Array Dereferencing in PHP

Array Dereferencing is really very good feature added in PHP 5.4. With this you can directly access an array object directly of a method a functions.

Now we can say that no more temporary variables in php now. This is becasue earlier we must have to take array in one variable then we can make further process on that array. Have a look at below example for what we were doing before PHP 5.4.

[cc lang=”php”]
$string = “Hello Expert Developer”;
// now we want to get second element
$tmp = explode(” “,$string);
echo $tmp[1]; // Expert
[/cc]

Now have a look at code block for how we can achieve this without temporary varibale:

[cc lang=”php”]
$string = “Hello Expert Developer”;
// now we want to get second element
echo explode(” “,$string)[1]; // Expert
[/cc]

Isn’t it really helpful??

No more temporary variables with arrays now!!!

Now have a look at be other benefetits of Array Dereferencing in PHP 5.4

As as above code you can deal with functions call also.

[cc lang=”php”]
function return_array()
{
return array(“Hello”,”Expert”,”Developer”);
}

// Now to get “Expert”

echo return_array()[1]; // Expert
[/cc]

For full list of Features included in PHP 5.4, have a look at this article.

Shares:
  • melek rebai
    melek rebai
    April 5, 2012 at 5:01 am

    yeah i did see the release notes of php 5.4 and i was really happy but also sad, you see the real problem is when the host is going to upgrade the PHP.
    :(

    Reply
    • Avinash
      April 5, 2012 at 9:28 am

      still it will take time to have the PHP 5.4 on server machines..

      Reply

Leave a Reply

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