tags:

views:

49

answers:

4

Im iterating through two lists dumping data into their own single array, but i need to merge the 2 arrays in numerical order into a single array.

Im using a counter (foreach and $i++) to name the keys in the proper order, but both operations leave me with arrays named with numbers 0-10.

How can i make a counter that will increment by only even or only odd numbers so i can merge the two lists after the fact and retain a proper numerical order?

ie, have the first loop name things 0-2-4-6-8-10, and the second loop count 1-3-5-7-9

+4  A: 

Add 2 to the variable in the for loop instead of 1. $i++ only increments by 1. Try $i=$i+2.

I don't think that's the only or best way to accomplish what you're trying to do, though. How about putting the numbers into two arrays, without worrying about making the keys mesh like that, then making a new array out of the combination of the two, in order?

$arr_one=array('a','c','e','g');
$arr_two=array('b','d','f','h');

$count=count($arr_one);
$combined=array();
for($i=0;$i<$count;$i++){
  $combined[]=$arr_one[$i];
  $combined[]=$arr_two[$i];
  }

$combined is now array ( 0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', 5 => 'f', 6 => 'g', 7 => 'h' )

Alex JL
thats actually a nice solution to the problem as a whole
Patrick
+3  A: 

Something like this should work-

$arr = array();
for($i=0; $i<=10; $i += 2) {
  $arr[] = $i;
}
sparkey0
+3  A: 

Mm... The first thing that comes to mind is

# Even
for ($i = 0; $i <= 10; $i=$i+2)
 {.... }

# Odd
for ($i = 1; $i <= 10; $i=$i+2)
 {.... }
Pekka
+2  A: 

increment the counter by two and start with zero or one

Tobias P.
simple answers...gotta love emthx mate
Patrick