A PHP Array Sort Problem With the Number Zero
PHP will generally act as expected when sorting values including numeric zero, sorting it as less than one and greater than any negative number. The most common sources of error when dealing with zero values stem from how they are used in arrays, or confusing a numeric zero value with the text "0" value.
-
Types of Arrays
-
An array is a single variable that holds a list of values. PHP has two kinds of arrays that differ in the way each is referenced by array commands. An array can have a numeric index in which each element of the array is assigned a sequential number, or it can use a keyed index in which a keyword is assigned to each element. For example, both of these are valid PHP arrays:
$family = array("John","Mary","Dick","Jane")
$family = array("father" => "John", "mother" => "Mary", "son" => "Dick", "daughter" => "Jane")
Zero-Based Indexes
-
PHP uses a zero basis for array indexing, which is the technical way of saying that instead of counting items starting with one, arrays are counted starting with zero. Common sense may indicate that $family[1] is "John", but this will result in "Mary". $family[0] is the numeric reference to use to return "John". Zero-based indexing frequently causes programming errors when one-based indexing is anticipated by the programmer, but this will rarely cause sorting errors since zero is sorted before one as would generally be expected.
-
String and Numeric Zero
-
A more likely cause of sorting errors involving zero is mixing text and numeric value types. PHP distinguishes between the text "0" and the number 0. This differs from other programming languages that use automatic coercion, where the language attempts to convert text containing numeric data into numbers when programming syntax mixes data types. PHP documentation states that sort routines will act erratically when data types are mixed, so confirm that all variables that you expect to hold numeric data actually do so.
Types of Sorting
-
PHP has different sort functions for sorting arrays by the contents of the array, or by the keywords assigned to array elements. PHP allows the assignment of the keyword "0" as a named element, which may differ from element 0 of the array. If you are sorting keys in an array, check your keys as well as your array data for mixed data types.
-