Day 6 – Lost in Arrays

Zend PHP Certification

I really didn’t expect to spend three (3) days on just arrays, but it seems like they are pretty important.  I just have to be careful not to fall behind, I still have ~9 more chapters after this and only ~24 days.  Well, instead of stressing about this now, let’s finish up arrays!


Array Sorting

It’s interesting to note that PHP uses QuickSort for all array sorting.

  • Basic Value-Based Sorting is done by the sort($array) function.  With this function, the array is passed by reference, sorted by whatever type order (numeric for numbers, alpha for strings), keys stripped off, and a simple key-incremented array is returned.
    $array = array(5 => “c”, 3 => “a”, 1 => “b”);
    1.  
    2. sort($array);
    3. // $array is now (0 => "a", 1 => "b", 2 => "c")

    You should be careful with the contents of your arrays when using these sorts.  If you mix types (e.g. numeric and string) you could have "unexpected results." You can also use asort($array) if you want to keep the key associations.

    If you want to sort your array in reverse order, you can use rsort($array) or arsort($array) for maintaining key associations.

    All of those functions can also have a second, optional parameter that specifies the search method.  By default, it doesn’t convert any data, so "10" will appear before "2" because they are strings and therefore order alphabetically.  You can force them to be converted and compared numerically by passing SORT_NUMERIC, or convert numbers to strings and sort alphabetically by passing SORT_STRING.

    If you are looking for a way to deal with text like "2 billion" and "10 billion," neither option will work for you.  But you can use natsort($array) to "naturally" sort it.  All key associations will be kept.  There is also a case-insensitive version, natcasesort($array).

  • Basic Key-Based Sorting is done by using the functions: ksort($array) and krsort($array) for reverse order.  This sorts the array by the keys instead of the values.  Both functions also accept the same optional parameter as the other functions.
  • User-Function Based Sorting involves writing a custom function and passing it to usort, uasort (keep key associations), and uksort (apply function to key instead of value).  The custom function needs to take in two variables, A and B, each referring to either a value (for usort) or a key (for uksort).  The function then needs to return 0 if they are equal, –1 if A is lower than B, and +1 is A is higher than B.  Here is an example:
    $array = array(“abc”, “bc”, “c”);
    1.  
    2. function sortSize($a, $b) {
    3.   if (strlen($a) == strlen($b))
    4.     return 0;
    5.   if (strlen($a) > strlen($b))
    6.     return -1;
    7.   return 1;
    8. }
    9.  
    10. usort($array, 'sortSize');
    11. // Ending array is sorted by size ("c", "bc", "abc")
  • Anti-Sorting (aka, Shuffling) is done simply with the shuffle($array) function.  The result is the same array but with the values randomly shuffled.  All key associations are lost.  There is also a function to extract random keys from an array, array_rand($array, $num).  This will return an array of $num random keys extracted from $array.  It will not remove them from the array.

Arrays as Various Data Objects

PHP allows you to treat an array as various things.  So far, we’ve been able to access arrays as a standard iterative array and an associative array.  Now we’ll treat them like stacks, queues, and sets.

  • Stacks follow the LIFO procedure (Last In, First Out).  So to replicate that, we can use the function array_push($array, $item) to add a value to the back of the array (*cough* stack).  And the function array_pop($array) to remove a value from the back of the array.  Note, popping returns the value that you removed.
  • Queues follow the FIFO procedure (First In, First Out).  PHP replicates this functionality with shifting and unshifting.  The function array_shift($array) returns and removes the first element of the array.  While the function array_unshift($array, $item) adds an element to the front of the array.
  • Sets are designed to check for common or different elements.  The function array_diff($array1, $array2) returns the values in $array1 that are not in $array2.  And the function array_intersect($array1, $array2) returns the values that are only in both arrays.  Keys are ignored from both functions, but there are, of course, functions to keep the associations: array_diff_assoc(), array_diff_uassoc() (for writing your own function), array_intersect_assoc(), array_intersect_uassoc().  And there are also functions for running these comparisons on the keys instead: array_diff_key(), array_diff_ukey(), array_intersect_key(), and array_intersect_ukey().

Again, so much stuff about Arrays.  I’ve covered the entire chapter, but I feel like they are missing a few things like: array_chunk(), array_fill(), array_merge(), array_map(), array_slice()… I could go on.  But that’s okay, this is what the guide said to cover, so I’ll stick with that for now.  Tomorrow is the String chapter!  Go Go Regular Expressions!

No Comments

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



  • Donate

    If my work has helped you and you want to return the favor, you could purchase something for me from my Amazon Wish List or send me a donation via PayPal.

  • License

    Unless otherwise noted, all source code and compiled files published on this website are released under the terms of the GNU Lesser General Public License.