mrpatg
mrpatg

Reputation: 10117

php increment numerical value variable by even or odd numbers

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

Upvotes: 0

Views: 3278

Answers (4)

Tobias P.
Tobias P.

Reputation: 4664

increment the counter by two and start with zero or one

Upvotes: 4

Pekka
Pekka

Reputation: 449475

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)
 {.... }

Upvotes: 3

sparkey0
sparkey0

Reputation: 1690

Something like this should work-

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

Upvotes: 4

JAL
JAL

Reputation: 21563

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' )

Upvotes: 4

Related Questions