zend php 5 certification study guide

Page 84

Arrays � 65

As you can see, usort() has lost all key-value associations and renumbered our array; this can be avoided by using uasort() instead. You can even sort by key (instead of by value) by using uksort(). Note that there is no reverse-sorting version of any of these functions—because reverse sorting can performed by simply inverting the comparison rules of the user-defined function: function myCmp ($left, $right) { // Reverse-sort according to the length of the value. // If the length is the same, sort normally

if (!$diff) { return strcmp ($right, $left); } return $diff; }

This will result in the following output: array(4) { [0]=> string(5) [1]=> string(4) [2]=> string(3) [3]=> string(3) }

"three" "2two" "two" "one"

The Anti-Sort There are circumstances where, instead of ordering an array, you will want to scramble its contents so that the keys are randomized; this can be done by using the shuffle() function:

Licensed to 39713 - Mihails Tumkins (mihailt@gmail.com)

$diff = strlen ($right) - strlen ($left);


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.