开发者

array looping strange behavior in php

I have an indexed array which I've generated from an associative array with this code

$index_arr = array();
foreach($assoc_arr as $key => $val ){
   $index_arr .= $val;
}

when I print it with print_r($index_arr); it works fine. But when I try to print it with foreach I get an error "Invalid argument supplied for foreach()"

foreach($index_arr as $one){
   echo "one: $one<br />";
}

I'm pretty s开发者_Go百科ure this is the right syntax or am I too tired at this time of day?


You turn the array into a string by using .= operator on it. You want to use:

$index_arr[] = $val;

To append to the end.

Also in this particular case, you can just do:

$index_arr = array_values($assoc_arr);

This does exactly what your loop does.


When you did $index_arr .= $val; PHP did a String operation. You need to do $index_arr[]=$val;


Needs to be this:

$index_arr = array();
foreach($assoc_arr as $key => $val ){
   $index_arr[] = $val;
}

Also

foreach($index_arr as $key=>$data){
   echo "Key: ".$key." Data: ".$data."<br />";
}


$index_arr .= $val;

should be

$index_arr[] = $val;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜