Warning: Increment on type bool has no effect, Need an explanation as to why $i is considered a boolean

156 Views Asked by At

This is a code snippet from a php function used in a software package I installed:

    $i = 0;
    $extra_small_header_field_values = array();
    while ($i < $i_len && $i !== false) {
        /* get argument */
        $read = trim(substr($read,$i));
        $i_len = strlen($read);
        $i = strpos($read,' ');
        $arg = substr($read,0,$i);
        ++$i;

The line containing ++$i; results in a warning Increment on type bool has no effect,.

My question is why is $i considered a boolean here? I realize that in PHP a boolean is a special class of integer but how does $i get to be considered a boolean given its evident prior treatment as an integer in the preceding code? How is this issue most correctly addressed?

2

There are 2 best solutions below

0
Dominik Miskovic On BEST ANSWER
$i = 0;
$extra_small_header_field_values = array();
while ($i < $i_len && $i !== false) {
    $read = trim(substr($read, $i));
    $i_len = strlen($read);
    $i = strpos($read, ' ');
    if ($i === false) {
        break;
    }
    $arg = substr($read, 0, $i);
    ++$i;
}

This should work for you.

The problem is because of how $i is used in the while loop the condition checks if $i is not equal to false and if it is, the loop stops. But here's the catch if the loop terminates because $i becomes false the next time around it tries to increment a boolean value and that's a not good, triggering the warning. To fix this, you need to make sure you're not trying to increment a boolean variable.

1
Joaquin Javi On

Here a link of the RFC : https://wiki.php.net/rfc/saner-inc-dec-operators.

PHP's increment and decrement operators can have some surprising behaviours when used with types other than int and float. Various previous attempts 1) 2) 3) have been made to improve the behaviour of these operators, but none have been implemented. The goal of this RFC is to normalize the behaviour of $v++ and $v-- to be the same as $v += 1 and $v -= 1, respectively.

Simply change ++$i to $i += 1;