2

This is something I haven't seen before but it appears to be supported and it does work, referencing the returned array key directly after the providing function is called. BUT... is this good practice? Will this be supported in the future? Does this even have a name?

<?php

function example_function() {
    $return = array('part_1', 'part_2');
    return $return;
}

$var = example_function()[0];

echo $var;

To get the same result I would normally do the following

$var = example_function();
$var = $var[0];
John Conde
  • 217,595
  • 99
  • 455
  • 496
MikeG
  • 314
  • 3
  • 11

2 Answers2

3

It's called Array Dereferencing. It has been available since PHP 5.4. It is acceptable to use although some might say it reduces readability.

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • 1
    @MikeG if you do not use it you might end http://stackoverflow.com/a/10470579/3882178 – loveNoHate Oct 08 '14 at 13:44
  • 1
    Personally, I find that it improves readability to an extent though I've found there's a few nanoseconds difference in dereferencing – Daryl Gill Oct 08 '14 at 13:45
0

Use it only when you are sure that you will always get array to work on. Sometimes ago I've have following code in some scraper class:

$ip = $this->getIP()[0];

I didn't check whether this function could return string and it caused some logic errors. Nowadays each time when I want to get array's item I do

$ip = $this->getIP()

if(is_array($ip)) {
    $ip = $ip[0];
} else {
    throw new Exception('Expects array here')
}
Mateusz Nowak
  • 4,021
  • 2
  • 25
  • 37