In my previous post i have discussed new features of PHP 5.4 such as concept of Traits and shorter syntax of array.
In this post i’ll discuss the concept of function array dereferencing which is introduced in PHP 5.4. In simple words function array dereference means when array is returned, pick the value directly from it.
Most Used Array Functions in PHP
Function Array Dereferencing
Let’s understand through example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
$product = "16789,7823,89123,7891"; // First store the result of explode in prod_id variable $prod_ids = explode(",", $product); print_r($prod_ids); // Output Array ( [0] => 16789 [1] => 7823 [2] => 89123 [3] => 7891 ) /*If you want to access 0th element of an array, then you need to do*/ echo $prod_ids[0]; |
In previous version of PHP, to dereference array temporary variable is used. We can’t directly array dereference the result of a function.
But in PHP 5.4 you can do this thing directly without storing the value in another variable.
1 2 |
$product = "16789,7823,89123,7891"; echo explode(",", $product)[0]; |
Let’s take another example.
1 2 3 4 5 6 7 8 9 10 |
function getProductIds() { // Your code return array(4562,15678,9245,5436); } // Pick third element of an array. echo getProductIds()[2]; |