PHP 5.4 – Function Array Dereferencing

PHP now supports array dereferencing directly from a function call.
Prior to version 5.4 you had to store the returning value from a function into a variable, and then use the variable.
The most frequent uses will be when using ‘preg_match’ or ‘explode’ kind of functions, functions that return an array. So instead of the following:

$data  = "piece1 piece2 piece3 piece4";
$pieces = explode(" ", $data);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

We could instead shorten this to:

$data  = "piece1 piece2 piece3 piece4";
echo explode(" ", $data)[0];

Another example using the ‘getdate()’ function.

# Without Function Array dereferencing

date_default_timezone_set('Asia/Kolkata');

$temp = getdate();

echo $temp['year'];
echo $temp['mon'];

# With Function Array dereferencing

date_default_timezone_set('Asia/Kolkata');

echo getdate()['mon'];
You can use the above in a conditional as shown below:
date_default_timezone_set('Asia/Kolkata');

if(getdate()['mon'] == 4) {
    echo "Month of April";
}

Another example using a custom function.

function getColors ()
{
  return [
          'red' => '#FF0000',
          'green' => '#00FF00',
          'blue' => '#0000FF'
         ];
}

echo getColors()['green']; // returns #00FF00

Leave a Reply

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

*