0

I have foreach loop in which I need to assign coordinates after certain steps. For this example $n+4 (174,178,182,...). I know that solve multiple entering n++.

$n = 174;
foreach($items as $item){
    echo $item . ' coor: ' . $n . '<br>';
    $n++;
    $n++;
    $n++;
    $n++;
}

I wonder if it can not be solved more elegantly.

2 Answers 2

2

You can use:

$n += 4;

When you put an operator before =, it creates an operator that combines the original value of the target with the source using that operation, so that's equivalent to:

$n = $n + 4;

Similarly, if you write:

$n *= 10;

it's the same as

$n = $n * 10;
Sign up to request clarification or add additional context in comments.

Comments

0

@Barmar 's solution and explanation is correct and solves your issue. But here is an alternative way you could write that code which you may find helpful:

$n = 174;
foreach($items as $i => $item){
    echo $item . ' coor: ' . $n + $i*4 . '<br>';
}

Note this will only work if your array keys are numeric and incrementing. If they're not then you just need to change $items in the foreach to array_values($items).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.