skip to Main Content

PHP-8.3.1

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

Answers


  1. 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;

    Login or Signup to reply.
  2. $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) {
            $arg = substr($read, 0, $i);
            ++$i;
        } else {
            break;
        }
    }
    

    this should work for u

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search