1.2.486. Function Subscripting

It is possible to use the result of a methodcall directly as an array, without storing the result in a temporary variable.

This works, given that the method actually returns an array.

This syntax was not possible until PHP 5.4. Until then, it was compulsory to store the result in a variable first. Although this is now superfluous, it has been a standard syntax in PHP, and is still being used. Storing the result in a variable is still useful if the result is actually used more than once.

<?php

function foo() {
    return array(1 => 'a', 'b', 'c');
}

echo foo()[1]; // displays 'a';

// Function subscripting, the old way
function foo() {
    return array(1 => 'a', 'b', 'c');
}

$x = foo();
echo $x[1]; // displays 'a';

?>

See also Accessing array elements with square bracket syntax.

1.2.486.1. Specs

Short name

Structures/FunctionSubscripting

Rulesets

All, Appinfo, CE, CompatibilityPHP53

Exakat since

0.8.4

PHP Version

With PHP 5.4 and more recent

Severity

Minor

Time To Fix

Instant (5 mins)

Precision

High

Features

subscripting

Available in

Entreprise Edition, Community Edition, Exakat Cloud