This question already has answers here:
Array dereferencing doesn't work [duplicate]
(5 answers)
Closed 6 years ago.
I got an error on this line of code which uses dereferencing:
$data['data'] = $results->result()[0];
(I started learning PHP with PHP 5.4.) How can I dereference in a 5.3 manner?
I have checked the docs:
function getArray() {
return array(1, 2, 3);
}
// on PHP 5.4
$secondElement = getArray()[1];
// before PHP 5.4
$tmp = getArray();
$secondElement = $tmp[1];
// or
list(, $secondElement) = getArray();
but creating a method call seems cumbersome
list() is what you want. It's been around forever and works great assuming the value on the right can be accessed by integer keys.
<?php
list(, $one, , $three) = range(0, 4);
Note that list() does not iterate the keys (as foreach would), but accesses integer keys by slot position (0, 1, ...) directly. If those keys don't exist you'll get a NOTICE and your value set to null.
$res = $results->result();
$data['data'] = $res[0];
Or you can use reassignment (to avoid the need for temporary variables):
$data['data'] = $results->result();
$data['data'] = $data['data'][0];