Saturday, November 15, 2014

Detail About Function Array Dereferencing in PHP 5.4

Get the detail concept of function array dereferencing which is first time introduced in PHP 5.4.Function array dereferencing means when array is returned, pick the value directly from it.

Most Famous Array Function in PHP

Function Array Dereferencing

Function Array Dereferencing in PHP 5.4

Check out the below example to understand more in detail.

$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];

We used dereference array temporary variable in the previous version of PHP. We can’t directly array dereference the result of a function.

But now in PHP 5.4 you can do this thing directly without storing the value in another variable.

$product  = "16789,7823,89123,7891";
echo explode(",", $product)[0];

Let’s take another example.

function getProductIds() {

// Your code

return array(4562,15678,9245,5436);
}

// Pick third element of an array.

echo getProductIds()[2];

0 comments:

Post a Comment