10

Ok, so I have a form that is sending me arrays in the POST array. I am trying to read it like so:

$day = $this->input->post("days")[0];

This does not work. PHP says "unexpected '['". Why does this not work?

I fixed it by doing it this way:

$days = $this->input->post("days");
$day = $days[0];

I fixed my problem, I'm just curious as to why the 1st way didn't work.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • Here's some SO discussion on the topic: http://stackoverflow.com/questions/742764/php-syntax-for-dereferencing-function-result – Dan U. Jun 24 '10 at 18:13

5 Answers5

9

Array derefencing from function calls isn't supported by PHP. It's implemented in the SVN trunk version of PHP, so it will likely make it into future versions of PHP. For now you'll have to resort to what you're doing now. For enumerated arrays you can also use list:

list($day) = $this->input->post("days");

See: http://php.net/list

Daniel Egeberg
  • 8,359
  • 31
  • 44
  • In addition to this answer, Please check this http://stackoverflow.com/a/22652521/567854 also in case the array is an **`associative array`** :) – Ijas Ameenudeen Apr 04 '14 at 03:50
  • Since PHP 5.4, array derefencing is supported. The following will work: `$day = $this->input->post("days")[0];` – liamja Oct 17 '15 at 16:49
8

Syntax like this:

$day = $this->input->post("days")[0];

isn't supported in PHP. You should be doing what you are doing:

$days = $this->input->post("days");
$day = $days[0];
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
7

Another approach could be to iterate through the array by using foreach like so:

foreach($this->input->post("days") as $day){
    echo $day;
}
Matthew
  • 7,440
  • 1
  • 24
  • 49
1

In addition to Daniel Egeberg's answer :

Please note that list() only works with numerical arrays. If you/anyone want to read an associative array like,

$_POST['date'] = array
                 (
                    'day'   => 12
                    'month' => 7
                    'year'  => 1986
                 )

use extract() function on above array as,

extract($this->input->post("date"), EXTR_PREFIX_ALL, "date");

Now the following variables will be available to use as,

$date_day = 19, $date_month = 7 and $date_year = 1986

NOTE: in the above function, first argument is the post array, second one is to protect from variable collisions and the third is the prefix.

For more on extract(), refer this.

Hope this helps :)

Community
  • 1
  • 1
Ijas Ameenudeen
  • 9,069
  • 3
  • 41
  • 54
-1

I would always do like this..

for($i=0; $i<count($this->input->post("days")); $i++)
{
  $day[$i] = $this->input->post("days[".$i."]");
}

This would be helpful if you need to interact with the db by checking each values passed by your view as an array. Otherwise I prefer foreach loop.

Cheers..

Raghu Acharya
  • 196
  • 1
  • 13