drummer
drummer

Reputation: 1221

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

Upvotes: 1

Views: 89

Answers (4)

Phill Pafford
Phill Pafford

Reputation: 85378

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 />";
}

Upvotes: 2

dnagirl
dnagirl

Reputation: 20446

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

Upvotes: 2

reko_t
reko_t

Reputation: 56450

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.

Upvotes: 5

Powerlord
Powerlord

Reputation: 88836

$index_arr .= $val;

should be

$index_arr[] = $val;

Upvotes: 1

Related Questions