2

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

6
  • yes, it's cumbersome in 5.3. That's why they introduced the deref feature in 5.4 to make it less cumbersome. I guess there's no chance you can update your server to 5.4? (mind you, I guess you should be greatful for that -- plenty of people posting here are stuck on 5.2 or even worse)
    – SDC
    Feb 5, 2013 at 16:26
  • Well, Im using a shared server which has the option of 5.2 or 5.3. In order to update to a dedicated server I would have to renew and pay closer to $170. Of course I could put 5.4 on the server, but it didn't take too long to remove the de-referencing. Feb 5, 2013 at 17:31
  • 1
    Why is it that hosting providers drag their feet on releases that have been out for close to a year? Feb 5, 2013 at 17:32
  • Which method call are you talking about? list() is a language construct, not a function. And never a method.
    – hakre
    Jul 13, 2013 at 8:34
  • Is PHP corrupts your mind if it was version 4.x and it was your first language? May 12, 2015 at 15:23

2 Answers 2

1

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.

1
  • 1
    list is pretty much useless for higher indexes. list(, , , , , , , , $eight) = $arr; is just unreadable.
    – Pacerier
    Jul 20, 2015 at 18:06
1
$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];
1
  • thank you, right now it seems to rid the error, Ill check back after I have changed all the instances of that code Feb 5, 2013 at 16:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.