How to sort an array and first have elements starting with a number?

How can I sort this array

$available_databases=array("4.0.1","trunk","branch","4.1.0","4.0.3"); 

therefore the result

 4.1.0 4.0.3 4.0.1 branch trunk 
+4
source share
3 answers

You can use the built-in operations with PHP arrays and, for example, perform a big heavy lift for you, thereby eliminating a lot of apparent complexity:

 $names = preg_grep('/^\D/', $arr); $versions = preg_grep('/^\d/', $arr); usort($versions, 'version_compare'); usort($names, 'strcasecmp'); $sorted = array_merge(array_reverse($versions), $names); 
+2
source

You must use the usort function.

 $isVersion = function($a) { return is_numeric( str_replace('.', '', $a) ); }; $sortFunction = function($a, $b) use($isVersion) { if( $isVersion($a) && $isVersion($b) ) { return version_compare($b, $a); // reversed for your proper ordering } elseif( $isVersion($a) ) { return -1; } elseif( $isVersion($b) ) { return 1; } else { return strcasecmp($a, $b); } }; usort($yourArray, $sortFunction); 

The usort function allows you to use your own callback for comparison. I wrote one for you with the logic that you wanted: if both comparable elements are versions, it uses version_compare to compare them with the changed parameters, since you want it in descending order. If the second comparable item is a string and the first is a version, the version is considered “lower” than the string, and vice versa. If both elements are strings, it uses the strcasecmp comparison strcasecmp to determine the correct ordering.

Example usage: codepad

+5
source

This can be done using some array functions and several loops.

Example:

 <?php $arr = array("4.0.1", "trunk", "branch", "4.1.0", "4.0.3", "1.2", "1.31", "1.10", "1.4.5"); natsort($arr); $count = count($arr); $alpha = array(); $new_arr = array(); for($i = 0; $i < $count; $i++) { if(!is_numeric(str_replace('.', '', $arr[$i]))) { $alpha[] = $arr[$i]; } else { $new_arr[] = $arr[$i]; } $arr[$i] = null; } rsort($new_arr); sort($alpha); $new_arr = array_merge($new_arr, $alpha); var_dump($new_arr); ?> 

Demo here

+1
source

All Articles