Bifalgorithm post · Computer science one · Sorting

How can PHP arrays be sorted with sort() and usort()?

How can PHP arrays be sorted with sort() and usort()? (Computer science one · Sorting) — "PHP’s sort() function can be used to sort elements in ascending order…

Ideas in this flowchart

  • PHP provides functions for sorting array elements.
  • sort() sorts array elements in ascending order.
  • It is useful for arrays containing numbers or strings.
  • It does not work very well with mixed types or objects.
  • String example: ("banana", "Apple", "zebra", "apple", "bananas") becomes ("Apple", "apple", "banana", "bananas", "zebra").
  • Numeric example: (10, 8, 3, 12, 4, 42, 7, 108) becomes (3, 4, 7, 8, 10, 12, 42, 108).
  • usort() is a more versatile user-defined sorting function.
  • usort() accepts a comparator function that defines the element ordering.
  • The comparator is passed as a string containing its function name.
  • PHP function names are case insensitive, but matching the naming remains best practice.
  • usort() can sort integers in descending order with cmpIntDesc.
  • An array of Student instances can be sorted by name, ID, or GPA.
  • Sorting by name uses studentByNameCmp.
  • Sorting by ID uses studentIdCmp.
  • Sorting by GPA uses studentGpaCmp.
Feed/

How can PHP arrays be sorted with sort() and usort()?

No cover

Channel

Computer science one

1 page

"PHP’s sort() function can be used to sort elements in ascending order. This is useful if you have arrays of numbers or strings, but doesn’t work very well if you have an array of mixed types or objects.\n\n$arr = array(\"banana\", \"Apple\", \"zebra\", \"apple\", \"bananas\");\n\nsort($arr);\n\n//arr is now (\"Apple\", \"apple\", \"banana\", \"bananas\", \"zebra\")\n\n$arr = array(10, 8, 3, 12, 4, 42, 7, 108);\n\nsort($arr);\n\n//arr is now (3, 4, 7, 8, 10, 12, 42, 108)\n\nPHP provides a more versatile sorting function, usort() ( user defined sort ) that accepts a comparator function that it uses to define the ordering of elements. To pass a comparator function to the usort() function, we pass a string value containing the name of the comparator function we wish to use. Recall that function names in PHP are case insensitive, though it is still best practice to match the naming. Several examples of the usage of this function are presented in Code Sample 47.1.\n\n$arr = array(10, 8, 3, 12, 4, 42, 7, 108);\n\nusort($arr, \"cmpIntDesc\");\n\n//arr is now 108, 42, 12, 10, 8, 7, 4, 3\n\n//roster is an array of Student instances\n\n$roster = ...\n\n//sort by name:\n\nusort($roster, \"studentByNameCmp\");\n\n//sort by ID:\n\nusort($roster, \"studentIdCmp\");\n\n//sort by GPA:\n\nusort($roster, \"studentGpaCmp\");"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.