Skip to content

Mention that usort doesn't call the callback if the array has only one element? #4760

@alexislefebvre

Description

@alexislefebvre

From manual page: https://www.php.net/manual/en/function.usort.php


I was trying to debug a call to usort that was never called.

It took me some time to understand that it's possible to write broken code like this:

Example 1

<?php

$array = [
    ['name' => 'foo'],
];


usort($array, function ($a, $b) {
    throw new \Exception('hi');
    return strcmp($a['name'], $b['nope']);
});

Try it online: https://3v4l.org/jrMWX#vnull

Here, the exception is never thrown because the array contains only one element, so the inline function is never called.

Example 2

<?php

$array = [
    ['name' => 'foo'],
];

usort($array, function ($a, $b) {
    return this_method_does_not_exist();
});

Try it online: https://3v4l.org/sZVp9#vnull

Here, the fact that the function this_method_does_not_exist isn't defined is not an issue, like Example 1 the callback is not executed.

Proposal

Add a notice to usort (and the other functions that may have the same behaviour) that the callback is called only if there are 2 elements or more.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions