views:

73

answers:

2

I have an associative array as follows:

$myarray = array('a'=>array(), 'b'=>array(), 'c'=>array(), 'd'=>array());

I want to be able to get all pairs of elements in the array. If it wasn't an associative array, I would use nested for loops, like:

for($i=0; $i<count($myarray); $i++) {
  for($j=$i+1; $j<count($myarray); $j++) {
    do_something($myarray[$i], $myarray[$j]);
  }
}

I have looked at using foreach loops, but as the inner loop goes through ALL elements, some pairs are repeated. Is there a way to do this?

Thanks!

A: 

The array_values() function returns an integer-indexed array containing all the values, so you can use it to obtain a list that you can iterate with a for.

Otherwise you can 'destroy' the array this way:

 while($k = array_pop($my_array)) {
   foreach($my_array as $j){ 
     do_something($k, $j);
   }
 }
Iacopo
Thanks, I think that gave me the clue I needed. I used array_keys() rather than array_values() and then looped through the keys with 2 nested for loops.Success! :)
JohnL
A: 

Try:

$keys = array_keys($myarray);
$c = count($myarray);
foreach ($keys as $k => $key1) {
    for ($i = $k + 1; $i < $c; $i ++) {
        dosomething($myarray[$key1], $myarray[$keys[$i]]);
    }
}
ircmaxell