Studyon Minte9.com
ZCE 5.3




Sort



sort()

<?php $arr = array('da', 'b', 'c'); sort($arr); print_r($arr); // [ b, c, da ]
  natsort() - Sort an array using a "natural order" algorithm
<?php $arr = array('10t', '2t', '3t'); natsort($arr); print_r($arr); // Array ( [1] => 2t [2] => 3t [0] => 10t )
  natcasesort - case insensitive
<?php $arr = array('10t', '2T', '2t', '3t'); natsort($arr); print_r($arr); // [ 2T, 2t, 3t, 10t ] $arr = array('10t', '2T', '2t', '3t'); natcasesort($arr); // case-insensitive print_r($arr); // [ 2t, 2T, 3t, 10t ]
  usort() - Sort an array by values using a user-defined comparison function
<?php // This short script allows us to sort an array by a rather complicated set of rules // First, we sort according to the length of each element // Elements whose values have the same length are further sorted // using regular string comparison $arr = array('three', '2two', 'one', 'two'); function myCmp($left, $right) { if ($diff = strlen($left) - strlen($right)) { return $diff; } return strcmp($left, $right); } usort($arr, 'myCmp'); print_r($arr); // Array ( [0] => one [1] => two [2] => 2two [3] => three )
  array_filter() - Filters elements of an array using a callback function
<?php // If no callback is supplied, all entries of the $input's empty values are remove // Example 1 (callback) $arr = array(1,2,3,4,5,6); // return true if integer is odd (bitwise &) function odd($var) { return ($var & 1); } // return true if integer is odd function even($var) { return (!($var & 1)); } print_r(array_filter($arr, 'odd')); // Array ( [0] => 1 [2] => 3 [4] => 5 ) print_r(array_filter($arr, 'even')); // Array ( [1] => 2 [3] => 4 [5] => 6 ) // Example 1 bis (more compact) $result = array_filter(array(1,2,3), create_function('$x', 'return $x & 1;')); print_r($result); // [ 1, 3 ] // Example 2 (remove empty) // Without callback, will return only non emtpy values $input = array(0=>'a', 1=> false, 2=> null, 3=> 'b'); $output = array_filter($input); print_r($output); // [ a, b ]
  array_multisort() - Sort multiple or multi-dimensional arrays
<?php // Example 1 $arr1 = array(3,2,1); $arr2 = array(4,8,0); array_multisort($arr1, $arr2); print_r($arr1); // [ 1, 2, 3 ] print_r($arr2); // [ 0, 8, 4 ] // The entries in the second array // corespond to the identical entries in arr1 // Example 2 $arr = array( array("10", 11, 100, 100, "a"), array(1, 2, "2", 3, 1), ); array_multisort( $arr[0], SORT_ASC, SORT_STRING, $arr[1], SORT_DESC, SORT_NUMERIC); print_r($arr); // [ "10", 11, 100, 100, "a" ] // [ 1, 3, "2", 2, 1 ] // 1 coresponds to "a" // Example 3 $data = array( array('a' => 1, 'b' => 2), array('a' => 2, 'b' => 3), array('a' => 2, 'b' => 1), array('a' => 1, 'b' => 1), ); foreach ($data as $k => $v) { $a[$k] = $v['a']; $b[$k] = $v['b']; } array_multisort($a, SORT_DESC, $b, SORT_ASC, $data); /* ordered array will be: $data = array( array('a' => 2, 'b' => 1), array('a' => 2, 'b' => 3), array('a' => 1, 'b' => 1), array('a' => 1, 'b' => 2), ); */