Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, sort, sort_flags

Tags:

php

sorting

flags

I am studying sort_flags at this page on PHP Manual.

And I don't understand what difference each of these flags represents.

There are only 6 flags, can someone please help me to understand the difference between them. Maybe with some examples. I would be very thankful.

like image 933
Blanktext Avatar asked Jun 23 '12 09:06

Blanktext


1 Answers

Array used for testing:

$toSort = array(2, 1, "img1", "img2", "img10", 1.5, "3.14", "2.72");

Note that 3.14 & 2.72 are strings.

Using SORT_REGULAR flag (compare items normally):

Array
(
    [0] => 2.72
    [1] => 3.14
    [2] => img1
    [3] => img10
    [4] => img2
    [5] => 1
    [6] => 1.5
    [7] => 2
)

Using SORT_NUMERIC flag (compare items numerically, so 3.14 is sorted as number not a string):

Array
(
    [0] => img10
    [1] => img1
    [2] => img2
    [3] => 1
    [4] => 1.5
    [5] => 2
    [6] => 2.72
    [7] => 3.14
)

Using SORT_STRING flag (SORT_LOCALE_STRING works similary, but depends on current locale, all values are treated as strings):

Array
(
    [0] => 1
    [1] => 1.5
    [2] => 2
    [3] => 2.72
    [4] => 3.14
    [5] => img1
    [6] => img10
    [7] => img2
)

Using SORT_NATURAL flag (note order of img* strings, it is natural):

Array
(
    [0] => 1
    [1] => 1.5
    [2] => 2
    [3] => 2.72
    [4] => 3.14
    [5] => img1
    [6] => img2
    [7] => img10
)

SORT_FLAG_CASE can be combined with SORT_STRING or SORT_NATURAL to do case-insensitive sort e.g.:

// works like SORT_NATURAL but is case-insensitive
sort($toSort, SORT_NATURAL | SORT_FLAG_CASE);
like image 96
Zbigniew Avatar answered Nov 15 '22 13:11

Zbigniew