tags:

views:

46

answers:

4

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 sure this is the right syntax or am I too tired at this time of day?

+2  A: 

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 />";
}
Phill Pafford
not "[].=", simply "[]="
stereofrog
Or just use `$index_arr = array_values($assoc_arr);` :)
Lukáš Lalinský
Thanks @Lukas just thought of that and was on my way back to edit, Cheers
Phill Pafford
+1  A: 
$index_arr .= $val;

should be

$index_arr[] = $val;
R. Bemrose
+5  A: 

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.

reko_t
+2  A: 

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

dnagirl