开发者

Getting data from post array in CodeIgniter

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 cu开发者_JAVA技巧rious as to why the 1st way didn't work.


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


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];


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

foreach($this->input->post("days") as $day){
    echo $day;
}


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 :)


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..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜