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

Pacerier
  • 86,231
  • 106
  • 366
  • 634
user1093111
  • 1,091
  • 5
  • 21
  • 47
  • 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 05 '13 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. – user1093111 Feb 05 '13 at 17:31
  • 1
    Why is it that hosting providers drag their feet on releases that have been out for close to a year? – user1093111 Feb 05 '13 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 '13 at 08:34
  • Is PHP corrupts your mind if it was version 4.x and it was your first language? – Brian Cannard May 12 '15 at 15:23
  • @user1093111, Because to upgrade and ensure everything works perfectly will cost energy and time. manpower = money, as your first comment stated. – Pacerier Jul 20 '15 at 06:00

2 Answers2

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];
Pacerier
  • 86,231
  • 106
  • 366
  • 634
Green Black
  • 5,037
  • 1
  • 17
  • 29
  • thank you, right now it seems to rid the error, Ill check back after I have changed all the instances of that code – user1093111 Feb 05 '13 at 16:07
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.

Steve Clay
  • 8,671
  • 2
  • 42
  • 48
  • 1
    `list` is pretty much useless for higher indexes. `list(, , , , , , , , $eight) = $arr;` is just unreadable. – Pacerier Jul 20 '15 at 18:06