Christopher Littlewood
Christopher Littlewood

Reputation: 803

How to increment by 1 and by 2 in PHP for loop

I am trying to increment two separate numbers in the same for loop. For example I want the first number to be:

0,2,4,6,8,10 etc

I want the second number to be:

1,3,5,7,9 etc

I have tried what was suggested here but could get it to work:

How to increment a number by 2 in a PHP For Loop

My code so far:

$count = count($toyList);
echo $count;
for($i=0; $i<$count; $i++){
    $json = '{"toy": {"toyname":"' . $toyList[$i+2] . ',"status":"' . $toyList[$i+3] . '"}}';
}

Any help would be greatly appreciated. Thanks.

Upvotes: 0

Views: 3152

Answers (1)

Koenigsberg
Koenigsberg

Reputation: 1798

Introduce an additional variable and increase that inside the loop after you have done with it whatever you intend to do. I don't have an environment for PHP at hand, but it should look something like this:

$count = count($toyList);
echo $count;
$j = 1;
for($i=0; $i<$count; $i++){
    $json = '{"toy": {"toyname":"' . $toyList[$i+2] . ',"status":"' .    $toyList[$i+3] . '"}}';
    $j = $j + 2;
}

Upvotes: 1

Related Questions