Skip to content

An assignment on the right of || in a while condition is possibly undefined after the loop #13765

Closed

Description

@orklah

A variable assigned on the right of || in a while condition is possibly undefined after the loop, although the loop only exits once the whole condition is false, so both operands were evaluated and the assignment ran:

<?php

/** @param array<int, int> $t */
function f(array $t, int $d): int {
    $s = 0;
    while (!($s > 3) || ($a = $t[$s] ?? 0) === $d) {
        $s++;
    }
    /** @psalm-check-type-exact $a = int */; // InvalidDocblock: Attempt to check undefined variable $a
    return $a; // PossiblyUndefinedVariable, MixedReturnStatement
}

https://psalm.dev/r/e08650e0d1

php-parser's ParserAbstract::doParse() has this pattern: its error recovery assigns $action in such a condition and reads it after the loop. Once a possibly undefined variable reads as T|null (#13762), this gives false PossiblyNullOperand / PossiblyNullArgument / PossiblyNullArrayOffset there.

Activity

  1. psalm-github-bot commented on Nov 14, 2026

    @psalm-github-bot

    I found these snippets:

    https://psalm.dev/r/e08650e0d1
    <?php
    
    /** @param array<int, int> $t */
    function f(array $t, int $d): int {
        $s = 0;
        while (!($s > 3) || ($a = $t[$s] ?? 0) === $d) {
            $s++;
        }
        /** @psalm-check-type-exact $a = int */;
        return $a;
    }
    Psalm output (using commit 5940d8a):
    
    ERROR: InvalidDocblock - 9:44 - Attempt to check undefined variable $a
    
    INFO: PossiblyUndefinedVariable - 10:12 - Possibly undefined variable $a, first seen on line 6
    
    INFO: MixedReturnStatement - 10:12 - Could not infer a return type
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions