Differences between SORT_REGULAR and SORT_STRING in php
One time I encountered a problem when using the php basic function asort:
"441469", "timestamp" => "1464334314" ]; asort($arr); var_dump($arr);?>
The result is as follows:
array(2) { ["nonce_str"]=> string(6) "441469" ["timestamp"]=> string(10) "1464334314"}
WTF?
No, why should 4 be sorted before 1? should strings not be sorted by string comparison?
Refer to the php.net reference document and find that the second parameter of the sort function is SORT_FLAG:
SORT_REGULAR-normal comparison unit (without changing the type)
SORT_NUMERIC-the unit is compared as a number.
SORT_STRING-the unit is compared as a string
SORT_LOCALE_STRING-compare the unit as a string based on the current region (locale) settings. you can use setlocale () to change it.
SORT_NATURAL-and natsort () sort the strings in "natural order. Added in PHP 5.4.0.
SORT_FLAG_CASE-it can be combined with SORT_STRING OR SORT_NATURAL (OR bit operation) without case-sensitive sorting strings.
The default sorting method is SORT_REGULAR. But what does "normal comparison unit" mean? What does "do not change the type" mean? since the type is not changed, my two strings should be arranged in the order of comparing strcmp strings. that is to say, the string "1464334314" should be before "441469! With these questions, I found the source code of php.
Source Code Analysis
Http://git.php.net /? P = php-src.git; a = blob_plain; f = ext/standard/array. c; hb = 42be298b3020337653cfcbdd87698b90006b2197
Php-src.git/ext/standard/array. c, 887:
/* {{{ proto bool asort(array &array_arg [, int sort_flags]) Sort an array and maintain index association */PHP_FUNCTION(asort){ zval *array; zend_long sort_type = PHP_SORT_REGULAR; compare_func_t cmp; if (zend_parse_parameters(ZEND_NUM_ARGS(), "a/|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } cmp = php_get_data_compare_func(sort_type, 0); if (zend_hash_sort(Z_ARRVAL_P(array), cmp, 0) == FAILURE) { RETURN_FALSE; } RETURN_TRUE;}/* }}} */
We can see that the function pointer for specific sequential control is cmp, which is obtained by passing sort_type to php_get_data_compare_func, and sort_type is a tag such as SORT_REGULAR/SORT_STRING.
Php-src.git/ext/standard/array. c, 632:
static compare_func_t php_get_data_compare_func(zend_long sort_type, int reverse) /* {{{ */{ switch (sort_type & ~PHP_SORT_FLAG_CASE) { // ... case PHP_SORT_STRING: if (sort_type & PHP_SORT_FLAG_CASE) { if (reverse) { return php_array_reverse_data_compare_string_case; } else { return php_array_data_compare_string_case; } } else { if (reverse) { return php_array_reverse_data_compare_string; } else { return php_array_data_compare_string; } } break; // ... case PHP_SORT_REGULAR: default: if (reverse) { return php_array_reverse_data_compare; } else { return php_array_data_compare; } break; } return NULL;}/* }}} */
In this function, we can see that SORT_REGULAR adopts php_array_data_compare for comparison, while SORT_STRING adopts php_array_data_compare_string for comparison.
Php-src.git/ext/standard/array. c, 370:
/* Numbers are always smaller than strings int this function as it * anyway doesn't make much sense to compare two different data types. * This keeps it consistent and simple. * * This is not correct any more, depends on what compare_func is set to. */static int php_array_data_compare(const void *a, const void *b) /* {{{ */{ // ... if (compare_function(&result, first, second) == FAILURE) { return 0; } ZEND_ASSERT(Z_TYPE(result) == IS_LONG); return Z_LVAL(result);}/* }}} */
Php-src.git/ext/standard/array. c, 465:
static int php_array_data_compare_string(const void *a, const void *b) /* {{{ */{ // ... return string_compare_function(first, second);}/* }}} */
Now we get two call chains:
SORT_REGULAR-> php_get_data_compare_func-> php_array_data_compare-> compare_function;
SORT_STRING-> php_get_data_compare_func-> php_array_data_compare_string-> string_compare_function;
SORT_REGULAR
Start with compare_function of the first entry:
Http://git.php.net /? P = php-src.git; a = blob_plain; f = Zend/zend_operators.c; hb = 42be298b3020337653cfcbdd87698b90006b2197
Php-src.git/Zend/zend_operators.c, 1818:
ZEND_API int ZEND_FASTCALL compare_function(zval *result, zval *op1, zval *op2) /* {{{ */{ // ... while (1) { switch (TYPE_PAIR(Z_TYPE_P(op1), Z_TYPE_P(op2))) { // ... case TYPE_PAIR(IS_STRING, IS_STRING): if (Z_STR_P(op1) == Z_STR_P(op2)) { ZVAL_LONG(result, 0); return SUCCESS; } ZVAL_LONG(result, zendi_smart_strcmp(Z_STR_P(op1), Z_STR_P(op2))); return SUCCESS; // ... } }}/* }}} */
SORT_REGULAR-> php_get_data_compare_func-> php_array_data_compare-> compare_function-> zendi_smart_strcmp;
Php-src.git/Zend/zend_operators.c, 2681:
ZEND_API zend_long ZEND_FASTCALL zendi_smart_strcmp(zend_string *s1, zend_string *s2) /* {{{ */{ int ret1, ret2; int oflow1, oflow2; zend_long lval1 = 0, lval2 = 0; double dval1 = 0.0, dval2 = 0.0; if ((ret1 = is_numeric_string_ex(s1->val, s1->len, &lval1, &dval1, 0, &oflow1)) && (ret2 = is_numeric_string_ex(s2->val, s2->len, &lval2, &dval2, 0, &oflow2))) {#if ZEND_ULONG_MAX == 0xFFFFFFFF if (oflow1 != 0 && oflow1 == oflow2 && dval1 - dval2 == 0. && ((oflow1 == 1 && dval1 > 9007199254740991. /*0x1FFFFFFFFFFFFF*/) || (oflow1 == -1 && dval1 < -9007199254740991.))) {#else if (oflow1 != 0 && oflow1 == oflow2 && dval1 - dval2 == 0.) {#endif /* both values are integers overflown to the same side, and the * double comparison may have resulted in crucial accuracy lost */ goto string_cmp; } if ((ret1 == IS_DOUBLE) || (ret2 == IS_DOUBLE)) { if (ret1 != IS_DOUBLE) { if (oflow2) { /* 2nd operand is integer > LONG_MAX (oflow2==1) or < LONG_MIN (-1) */ return -1 * oflow2; } dval1 = (double) lval1; } else if (ret2 != IS_DOUBLE) { if (oflow1) { return oflow1; } dval2 = (double) lval2; } else if (dval1 == dval2 && !zend_finite(dval1)) { /* Both values overflowed and have the same sign, * so a numeric comparison would be inaccurate */ goto string_cmp; } dval1 = dval1 - dval2; return ZEND_NORMALIZE_BOOL(dval1); } else { /* they both have to be long's */ return lval1 > lval2 ? 1 : (lval1 < lval2 ? -1 : 0); } } else { int strcmp_ret;string_cmp: strcmp_ret = zend_binary_strcmp(s1->val, s1->len, s2->val, s2->len); return ZEND_NORMALIZE_BOOL(strcmp_ret); }}/* }}} */
Here we can see that zendi_smart_strcmp first checks whether the two strings to be compared are represented in numbers. If yes, the string with the same number is compared as an integer or floating point type. if not, the string is compared using zend_binary_strcmp.
Php-src.git/Zend/zend_operators.c, 2791:
ZEND_API zend_uchar ZEND_FASTCALL _is_numeric_string_ex(const char *str, size_t length, zend_long *lval, double *dval, int allow_errors, int *oflow_info) /* {{{ */{ const char *ptr; int digits = 0, dp_or_e = 0; double local_dval = 0.0; zend_uchar type; zend_long tmp_lval = 0; int neg = 0; if (!length) { return 0; } if (oflow_info != NULL) { *oflow_info = 0; } /* Skip any whitespace * This is much faster than the isspace() function */ while (*str == ' ' || *str == '\t' || *str == '\n' || *str == '\r' || *str == '\v' || *str == '\f') { str++; length--; } ptr = str; if (*ptr == '-') { neg = 1; ptr++; } else if (*ptr == '+') { ptr++; } if (ZEND_IS_DIGIT(*ptr)) { /* Skip any leading 0s */ while (*ptr == '0') { ptr++; } /* Count the number of digits. If a decimal point/exponent is found, * it's a double. Otherwise, if there's a dval or no need to check for * a full match, stop when there are too many digits for a long */ for (type = IS_LONG; !(digits >= MAX_LENGTH_OF_LONG && (dval || allow_errors == 1)); digits++, ptr++) {check_digits: if (ZEND_IS_DIGIT(*ptr)) { tmp_lval = tmp_lval * 10 + (*ptr) - '0'; continue; } else if (*ptr == '.' && dp_or_e < 1) { goto process_double; } else if ((*ptr == 'e' || *ptr == 'E') && dp_or_e < 2) { const char *e = ptr + 1; if (*e == '-' || *e == '+') { ptr = e++; } if (ZEND_IS_DIGIT(*e)) { goto process_double; } } break; } if (digits >= MAX_LENGTH_OF_LONG) { if (oflow_info != NULL) { *oflow_info = *str == '-' ? -1 : 1; } dp_or_e = -1; goto process_double; } } else if (*ptr == '.' && ZEND_IS_DIGIT(ptr[1])) {process_double: type = IS_DOUBLE; /* If there's a dval, do the conversion; else continue checking * the digits if we need to check for a full match */ if (dval) { local_dval = zend_strtod(str, &ptr); } else if (allow_errors != 1 && dp_or_e != -1) { dp_or_e = (*ptr++ == '.') ? 1 : 2; goto check_digits; } } else { return 0; } if (ptr != str + length) { if (!allow_errors) { return 0; } if (allow_errors == -1) { zend_error(E_NOTICE, "A non well formed numeric value encountered"); } } if (type == IS_LONG) { if (digits == MAX_LENGTH_OF_LONG - 1) { int cmp = strcmp(&ptr[-digits], long_min_digits); if (!(cmp < 0 || (cmp == 0 && *str == '-'))) { if (dval) { *dval = zend_strtod(str, NULL); } if (oflow_info != NULL) { *oflow_info = *str == '-' ? -1 : 1; } return IS_DOUBLE; } } if (lval) { if (neg) { tmp_lval = -tmp_lval; } *lval = tmp_lval; } return IS_LONG; } else { if (dval) { *dval = local_dval; } return IS_DOUBLE; }}/* }}} */
The above code is a comparison function used to determine whether a string is in the "number" format.
SORT_STRING
Next let's take a look at the second call chain: SORT_STRING-> php_get_data_compare_func-> php_array_data_compare_string-> string_compare_function;
Php-src.git/Zend/zend_operators.c, 1729:
ZEND_API int ZEND_FASTCALL string_compare_function(zval *op1, zval *op2) /* {{{ */{ if (EXPECTED(Z_TYPE_P(op1) == IS_STRING) && EXPECTED(Z_TYPE_P(op2) == IS_STRING)) { if (Z_STR_P(op1) == Z_STR_P(op2)) { return 0; } else { return zend_binary_strcmp(Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_STRVAL_P(op2), Z_STRLEN_P(op2)); } } else { zend_string *str1 = zval_get_string(op1); zend_string *str2 = zval_get_string(op2); int ret = zend_binary_strcmp(ZSTR_VAL(str1), ZSTR_LEN(str1), ZSTR_VAL(str2), ZSTR_LEN(str2)); zend_string_release(str1); zend_string_release(str2); return ret; }}/* }}} */
We can see that SORT_STRING eventually uses the zend_binary_strcmp function for string comparison. The following code is the implementation of zend_binary_strcmp:
Php-src.git/Zend/zend_operators.c, 2539:
ZEND_API int ZEND_FASTCALL zend_binary_strcmp(const char *s1, size_t len1, const char *s2, size_t len2) /* {{{ */{ int retval; if (s1 == s2) { return 0; } retval = memcmp(s1, s2, MIN(len1, len2)); if (!retval) { return (int)(len1 - len2); } else { return retval; }}/* }}} */Summary
After the above analysis, we can know that the underlying implementation of SORT_STRING sorting method is memcmp in C language. that is to say, it compares the two strings one by one based on the bytes. Once the bytes are different, terminate and compare the size.
SORT_REGULAR intelligently determines the type of the object to be sorted. if both strings are strings in the form of "pure numbers, it is sorted by comparing the values of the decimal integers and floating-point numbers represented by the entire string. If the two strings are not in the "pure number" format, they will be the same as SORT_STRING.
Therefore, if you need to sort byte by byte in the strcmp string mode, you must use the flag SORT_STRING when calling the php sort function, otherwise, if the two strings are in the form of "pure numbers", they are sorted according to the numbers they represent.
Note that, if the two values have different types, such comparison is meaningless and may produce unexpected results.
Final test
Finally, we add a character "s" at the end of the value to be sorted so that they are no longer strings in the form of "pure numbers:
"441469s", "timestamp" => "1464334314s" ]; asort($arr); var_dump($arr);?>
The final sorting result is:
array(2) { ["timestamp"]=> string(11) "1464334314s" ["nonce_str"]=> string(7) "441469s"}
This is what we want.