Skip to content

Check for non-empty array is inconsistent/incomplete. #2142

@ahilke

Description

@ahilke

Bug report

Some expressions should trigger PHPStan to consider an array as not empty, but don't.
These seem to be non-strict comparisons (see below) and using sizeof instead of count (they are aliases).

Code snippet that reproduces the problem

<?php declare(strict_types = 1);

/**
* @param string[] $arr
*/
function doFoo(array $arr): string {
    if (count($arr) > 0) {
        return reset($arr); // Function doFoo() should return string but returns string|false
    }
}

Basically the same as in #1383 (the example there also throws an error).
A few more working and failing examples can be found here: https://phpstan.org/r/4f184387-bacb-4bda-9592-c04da6bc4d03

In general it seems that non-strict comparisons do not work as expected (==, !=, <, >).
Also, as already mentioned, sizeof is not considered either.

Expected output

All failing examples from the linked example should make PHPStan consider the array non-empty, i.e.

  • count($arr) > 0
  • count($arr) != 0
  • count($arr) == 1 (or any constant positive number)
  • $arr != []
  • sizeof($arr) !== 0

EDIT: Found another failing example (using sizeof instead of count), adjusted the ticket.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions