Why would sort fail?

我只是一个虾纸丫 提交于 2020-07-29 11:50:53

问题


I'm writing a library routine, which among other things will do some rather complex sorting of nested arrays.

I see from the documentation that all the array sort function (including the ones using built-in comparators) can return false on failure - but when would this ever be the case???


回答1:


It would fail when the variable you send to the function is NOT an array
Example:

asort('Hello');//fails
asort(array(1,2,35,7,2,8,3));//true



回答2:


I also stumbled upon this question and did some research, if there are other conditions, when sort returns false. A look into the code showed this sort function

PHP_FUNCTION(sort)
{
    zval *array;
    zend_long sort_type = PHP_SORT_REGULAR;
    compare_func_t cmp;

    ZEND_PARSE_PARAMETERS_START(1, 2)
        Z_PARAM_ARRAY_EX(array, 0, 1)
        Z_PARAM_OPTIONAL
        Z_PARAM_LONG(sort_type)
    ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);

    cmp = php_get_data_compare_func(sort_type, 0);

    if (zend_hash_sort(Z_ARRVAL_P(array), cmp, 1) == FAILURE) {
        RETURN_FALSE;
    }
    RETURN_TRUE;
}

On the first view, you see, that the sort function only returns false, if zend_hash_sort fails. zend_hash_sort is a macro, which actually calls zend_hash_sort_ex. This function was build pretty robust and returns SUCCESS in all cases - even if you pass arrays with totally uncompareable elements.

This leads us back to the sort function, which does some parameter checking with macros and has three rules.

  1. The function takes at least one argument and max 2 arguments.

  2. The first argument must be an array

  3. The second argument (if given) must be an long

So sort returns only false in case, one of this three rules is broken.

$a = false;
sort($a); // fails because of rule 2
$a = [];
sort($a, "test"); // failes because of rule 3
sort($a, 0, "test"); // failes because of rule 1



回答3:


When the parameter supplied is not an array (or maybe even just an empty array).




回答4:


examples of a return of false could include empty array, variable not an array, insufficient memory available, library call fail, runtime fail of the sorting module, call parameters not valid, disk pack or drive not online, sorting algorithm or method not compatible with rules of the region or country of development



来源:https://stackoverflow.com/questions/5354891/why-would-sort-fail

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!