Unclear scope of RSPEC-1155

Hi community :wave:,

To be honest, I am not 100% sure if I am posting this at the correct place.

Why do I think this rule is confusing/misleading?

count works with arrays and countable objects. Using count throws a TypeError if called with any other type as parameter. Replacing count with empty would remove such implicit fail-safe - empty accepts Strings, too.

After reading the PR changes it is not clear to me whether this rule only applies to variables that has been clearly identified as array or if it would also raise issues for countable objects. If the latter, empty would be no valid replacement as it returns false for countable objects.

Countable objects code sample

class CountMe implements Countable
    protected int $myCount = 0;

    public function count(): int
        return $this->myCount;

$countable = new CountMe();
var_dump(count($countable) === 0); // returns 0
var_dump(empty($countable)); // returns false

Suggested changes (discussion very welcome)

In case rule RSPEC-1155 only applies to arrays, it should be mentioned in the rule description. Maybe even referencing the very similar rule RSPEC-3981. Would it also be more type safe to check the emptiness of an array by comparing with an empty array instead of empty? If the variable does not hold an array, there should already be other checks conditions.


// code that provides $variableUnderTest
// ...

if ($variableUnderTest === []) {
  // handle empty array case

Best regards,

Hi @justus_bunsi,

Thank you for your detailed explanation.

The intention of this rule is performance and readability.

The empty() function in PHP is specifically designed to check if a variable is empty, and it returns true if the variable is empty or evaluates to false as you already identified. It handles various types of values, such as empty strings, zero, null, and arrays with no elements. This makes the code more readable because it clearly expresses the intention of checking for emptiness.

On the other hand, the count() function in PHP is primarily used to count the number of elements in an array or the properties of an object. It’s less explicit and may be less intuitive for someone reading the code.

In terms of performance, empty() is generally faster than count() because it doesn’t need to iterate over all the elements in an array to count them. Instead, it directly checks if the variable is empty or evaluates to false. This can be advantageous when dealing with large arrays or performance-sensitive code.

Your reference to RSPEC-3981 is interesting and I would ask you. Does it really make sense to use the count emptiness? We would also advise to not use the count() function to check the type of a variable.