Nested foreach loops for associative array combinations
Posted
by JohnL
on Stack Overflow
See other posts from Stack Overflow
or by JohnL
Published on 2010-06-09T15:47:40Z
Indexed on
2010/06/09
16:02 UTC
Read the original article
Hit count: 204
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!
© Stack Overflow or respective owner