Concept

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

ComputerScienceOne / Sorting

"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\");"

Related Ideas

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