Array Dereferencing in PHP

  • Avinash
  • 2
  • Mar 15, 2012
  • Web Development

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.

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

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

$string = "Hello Expert Developer"; // now we want to get second element echo explode(" ",$string)[1]; // Expert
  $string = "Hello Expert Developer";
  // now we want to get second element
  echo explode(" ",$string)[1]; // Expert

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.

function return_array() { return array("Hello","Expert","Developer"); } // Now to get "Expert" echo return_array()[1]; // Expert
  function return_array()
  {
    return array("Hello","Expert","Developer");
  }
 
  // Now to get "Expert"
 
  echo return_array()[1]; // Expert

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

Related Posts

Written by Avinash

Avinash Zala currently working at a leading web development company as a Sr. PHP Web Developer. He is the founder of the Xpert Developer. He has completed B.E. in Information Technology. Born and brought up in Ahmedabad. He loves to code and coding is all about passion for him. Follow him on twitter at Avinash Zala & Xpert Developer.

View all posts by:

  • melek rebai

    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.
    :(

    • http://www.xpertdeveloper.com Avinash

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