InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

Menu
  • Home
  • Sitemap

Python Programming Language Best Tutorials and Code Examples

Learn Python Right Now!
Home
PHP
Sorting an Array by a Computable Field in PHP
PHP

Sorting an Array by a Computable Field in PHP

InfinityCoder November 20, 2016

You want to define your own sorting routine.

Use usort() in combination with a custom comparison function:

1
2
3
4
5
6
$tests = array('test1.php', 'test10.php', 'test11.php', 'test2.php');
 
// sort in reverse natural order
usort($tests, function ($a, $b) {
     return strnatcmp($b, $a);
});

The comparison function must return a value greater than 0 if $a > $b, 0 if $a == $b, and a value less than 0 if $a < $b. To sort in reverse, do the opposite. The function in the Solution, strnatcmp(), obeys those rules.
To reverse the sort, instead of multiplying the return value of strnatcmp($a, $b) by -1, switch the order of the arguments to strnatcmp($b, $a).
The comparison function doesn’t need to be a wrapper for an existing sort or an anonymous function. For instance, the date_sort() function, shown in Example 4-2, shows how to sort dates.

Example 4-2 date_sort( ). 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// expects dates in the form of "MM/DD/YYYY"
function date_sort($a, $b) {
    list($a_month, $a_day, $a_year) = explode('/', $a);
    list($b_month, $b_day, $b_year) = explode('/', $b);
 
    if ($a_year > $b_year ) return 1;
    if ($a_year < $b_year ) return -1;
 
    if ($a_month > $b_month) return 1;
    if ($a_month < $b_month) return -1;
 
    if ($a_day > $b_day ) return 1;
    if ($a_day < $b_day ) return -1;
 
    return 0;
}
 
$dates = array('12/14/2000', '08/10/2001', '08/07/1999');
usort($dates, 'date_sort');

While sorting, usort() frequently recomputes the comparison function’s return values each time it’s needed to compare two elements, which slows the sort.

To avoid unnecessary work, you can cache the comparison values, as shown in array_sort() in Example 4-3.
Example 4-3. array_sort( )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function array_sort($array, $map_func, $sort_func = '') {
    $mapped = array_map($map_func, $array);     // cache $map_func() values
 
    if (=== $sort_func) {
         asort($mapped);                        // asort() is faster then usort()
        } else {
         uasort($mapped, $sort_func);           // need to preserve keys
}
 
    while (list($key) = each($mapped)) {
        $sorted[] = $array[$key];               // use sorted keys
}
 
    return $sorted;
}

To avoid unnecessary work, array_sort() uses a temporary array, $mapped, to cache the return values.

It then sorts $mapped, using either the default sort order or a userspecified  sorting routine. Importantly, it uses a sort that preserves the key/value relationship.

By default, it uses asort() because asort() is faster than uasort(). (Slowness in uasort() is the whole reason for array_sort() after all.)

Finally, it creates a sorted array, $sorted, using the sorted keys in $mapped to index the values in the original array.

For small arrays or simple sort functions, usort() is faster, but as the number of computations grows, array_sort() surpasses usort().

The following example sorts elements by their string lengths, a relatively quick custom sort:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function u_length($a, $b) {
    $a = strlen($a);
    $b = strlen($b);
 
    if ($a == $b) return 0;
    if ($a > $b)  return 1;
                  return -1;
}
 
function map_length($a) {
    return strlen($a);
}
 
$tests = array('one', 'two', 'three', 'four', 'five',
               'six', 'seven', 'eight', 'nine', 'ten');
 
// faster for < 5 elements using u_length()
usort($tests, 'u_length');
 
// faster for >= 5 elements using map_length()
$tests = array_sort($tests, 'map_length');

Here,array_sort() is faster than usort() once the array reaches five elements.

 

Share
Tweet
Email
Prev Article
Next Article

Related Articles

Parsing Complex XML Documents in PHP
You have a complex XML document, such as one where …

Parsing Complex XML Documents in PHP

Detecting SSL in PHP
You want to know if a request arrived over SSL. …

Detecting SSL in PHP

About The Author

InfinityCoder
InfinityCoder

Leave a Reply

Cancel reply

Recent Tutorials InfinityQuest

  • Adding New Features to bash Using Loadable Built-ins in bash
    Adding New Features to bash Using Loadable …
    June 27, 2017 0
  • Getting to the Bottom of Things in bash
    Getting to the Bottom of Things in …
    June 27, 2017 0

Recent Comments

  • fer on Turning a Dictionary into XML in Python
  • mahesh on Turning a Dictionary into XML in Python

Categories

  • Bash
  • PHP
  • Python
  • Uncategorized

InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

About Us

Start learning your desired programming language with InfinityQuest.com.

On our website you can access any tutorial that you want with video and code examples.

We are very happy and honored that InfinityQuest.com has been listed as a recommended learning website for students.

Popular Tags

binary data python CIDR convert string into datetime python create xml from dict python dictionary into xml python how to create xml with dict in Python how to write binary data in Python IP Address read binary data python tutorial string as date object python string to datetime python

Archives

  • June 2017
  • April 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
Copyright © 2021 InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more
Programming Tutorials | Sitemap