swoole / library

📚 Swoole Library
https://wiki.swoole.com/#/library
Apache License 2.0
237 stars 58 forks source link

Add ArrayObject::isAssoc() #58

Closed leocavalcante closed 3 years ago

leocavalcante commented 3 years ago

Checks whether the given array wrapped by ArrayObject is associative (uses string keys like a hashmap).

deminy commented 3 years ago

The Swoole team had discussed the implementations of this particular method two months ago. It's always inefficient when implemented in PHP, like the one implemented in Laravel ( https://github.com/laravel/framework/blob/v8.9.0/src/Illuminate/Collections/Arr.php#L389 ). Although there were thoughts like comparing keys in reverse order, it doesn't help much in worse cases.

Let's see how others think. Thanks @leocavalcante for the PRs!

twose commented 3 years ago

The best way is https://github.com/php/php-src/pull/6070

$index = count($array);
reverse_foreach($array as $key => void) {
    if ($key !== --$index) {
        return false;
    }
    return true;
}
deminy commented 3 years ago

According to this PHP RFC (_Add array_islist(array $array): bool), a new PHP function _array_islist() will be added to PHP 8.1. This new function can be found in the Docker image for PHP nightly (8.1-dev only):

docker run --rm -ti phpdaily/php:8.1-dev php -r 'echo function_exists("array_is_list") ? "yes" : "no", "\n";'

As discussed, the same function written in PHP is much less efficient compared to a built-in PHP function like _array_islist(). Thus, we prefer not to add method ArrayObject::isAssoc() to the Swoole library; developers can add and use this method (or some variations) manually in their projects when needed.

Thanks again to @leocavalcante for submitting the PR and for contributing to the open source community!