Home » Php » Multiple comparisons inside for loops don't break php code. Why?

Multiple comparisons inside for loops don't break php code. Why?

Posted by: admin February 25, 2020 Leave a comment

Questions:

Why this piece of code works when it is clearly wrong in the second for loop (for ($i==0; $i<$parts; $i++) {)?
Does php allows for multiple comparisons inside for loops?

function split_integer ($num,$parts) {
    $value = 0;
    $i = 0;
    $result = [];
    $modulus = $num%$parts;

    if ($modulus == 0) {
        for($i = 0; $i < $parts; $i++)
        {
            $value = $num/$parts;
            $result[] = $value;
        }
    } else {
        $valueMod = $parts - ($num % $parts);
        $value = $num/$parts;

        for ($i==0; $i<$parts; $i++) {
            if ($i >= $valueMod) {
                $result[] = floor($value+1);
            } else {
                $result[] = floor($value);
            }
        }
    }
    return $result;
}
How to&Answers:

Code for ($i==0; $i < $parts; $i++) runs because $i==0 has no impact on loop.

In normal for loop first statement just sets $i or any other counter’s initial value. As you already set $i to 0 earlier, your loop runs from $i = 0 until second statement $i < $parts is not true.

Going further, you can even omit first statement:

$i = 0;
for (; $i < 3; $i++) {
    echo $i;
}

And loop will still run 3 times from 0 to 2.