PHP Arrays 102

Feature: PHP has quite an array of Array functions.

In our previous overview of PHP arrays we emphasized the associative arrays with their string keys and the ability to handle any sort of value including booleans, strings, numbers, other arrays, and class instances or objects. This versatility is one of the aspects of arrays that make them attractive.

However, as it turns out there are two types of arrays as far as PHP functions are concerned: 1)integer numbered or index arrays as in: $ix = array ( 1, 2, 4, 8, 16); and 2)associative arrays. Index arrays preceeded associative arrays and are simpler to work with. And thus many of the PHP array functions work primarily or only with index arrays. This is fine because developers will have many occasion to use index arrays. But associative arrays are also becoming a more common occurrence in PHP starting with database files with their fieldname keys and data field values or XML files with tagname as key and text element as value. So this tutorial will look at the most useful index array functions, then the functions to avoid if you are using associative arrays because they destroy associative keys, and then a few good associative array functions. As previously we will be using the Command Line interface of PHP 5 to test out our array functions.

Index Array Functions

One of the small golden grails of data structures is to have a stack/queueing mechanism that is able to handle any type of contents be they numbers, strings, arrays, objects - just push and pop them from the stack (queue or dequeue them from the deque). Well with PHP's array functions look no further - as long as you are not worried about associative key-value pairs. In the latter case you may have to use 2 valued arrays or extended push/shift functions - in effect do a lot of the work yourself. But otherwise, the following PHP array functions will do fine indeed:
  - array_pop($stack) - returns the last stack item pushed and deletes the entry from the stack; if the stack is empty it returns NULL;
  - array_push($stack, $value, ...) - appends to the end or top of the stack the value(s) supplied;
  - array_peek($stack, [$where]) - returns a peek of what is on $where in the stack but does not delete it; returns NULL if the stack is empty. Second argument is optional. We have to roll our own as follows:

function array_peek($stack, $where){
  //First see if the stack is empty
  if($cnt==0)return NULL;
  //Then set $where to top of stack if it is omitted
  if(func_num_args() <= 1)$where = $cnt-1;
  //Next make sure $where is pointing to somewhere in the stack -
  //otherwise make it point to the top of the stack
  if($where >= $cnt || $where<0)$where = $cnt-1;
  return $stack[$where];
- array_shift($stack) - returns the deepest (bottom but in this case the first item in the array is the bottom of the stack because stacks are LIFO-Last In First Out while queues are FIFO - First In First Out) item from the stack and deletes it from the stack; if the stack is empty it returns NULL;
  - array_unshift($stack, $value, ...) - prepends to the bottom of the stack the value(s) included in the call; returns the number of items added or NULL if it fails;
  - in_array($mixed_value, $stack, [$bool_type_check]) - is a very powerful search agent for finding specific values in the stack. $mixed_value can be any number, string, array, or class instance/object. If the optional $bool_type_check argument is set to true the type of $mixed_value also has to match the stack entry.

So there you have a basic set of stack/queue functions that work well with indexed arrays. In the screen shot below you see the array functions in action being used with PHP 5's hot new SimpleXML function to process a MenuList read from an XML configuration file.

The following is a list of other indexed array functions that can be useful in PHP programs:
  - array_pad($arr, $total_size, $mixed_value) - pads out the array with $mixed_value (which can be an array or object) to $total_size if that is greater then current size of array; otherwise nothing is done. If $total_size is negative the values are prepended; otherwise they are appended;
  - range($low, $high) - creates an array of integer values from $low, incremented by 1 to $high

Array Mal-Functions

Here is a list of array functions which do not always work as might be expected. For example, some will convert to integer or destroy an associative array's keys. So be careful when you use the following array functions:
  -array_count_value($arr) - counts the number of unique values in an array; very useful with subfields in databases like state or
  - array_flip($arr) - exchanges key for value and vice versa; but values that are arrays and objects are clipped to a single value;
  - array_intersect($arr, ...) returns an array of common elements in the list of arrays; however it does not compare keys and if they differ the second key is destroyed;
  - array_splice($arr, $offset, [$length], [$replaceArray]) at $offset the elements in $arr are replaced for $length with values in $replaceArray. Problem-any associative keys in $replaceArray are converted to integers;
  - array_unique($arr) - eliminates all duplicate values in array; but mishandles array and object values only retaining first value encountered(its a mess in this case);
  - rsort($arr) - sorts the array in descending order but converts keys to integers;
  - shuffle($arr) - randomly shuffles the values in the array; use array_rand() for associative safe "shuffle";
  - sort($arr, [$flag]) - sorts the array by value; optional $flag tells how to do sort - but converst keys to integers;
  - usort($arr, string 'func') - allows sorting array by user defined 'func'; use uasort() if associative array key values must be preserved;

Associative Array Functions

The following basic navigation functions work with both index and associative arrays. Note that they do presume that the array has been sorted by keys. Also note that every array has associated with it a pointer. That pointer changes with many array operations. When an array is created or sorted the pointer is set to point to the first or topmost item in the array. The operations like next(), prev() move the pointer along. Remember from our previous tutorial that iteration through an array is possible and many times expedited with the foreach command. Here are the basic array navigation commands:
  - current($arr) - returns the current value of $arr without moving the pointer;
  - each($arr) - an array with two copies of the current key-value pair; the advances the pointer to the next item or returns false if its point beyond the array end;
  - end($arr) - moves the pointer to the last item in the array and returns that value or boolean false if the array is empty;
  - key($arr) - returns the key of the current element the array pointer is on or boolean false if the array is empty. It does not change the array pointer;
  - next($arr) - advances the array pointer first, then returns the value or boolean false if beyond the end of the array;
  - prev($arr) - moves the pointer back one element in array first then returns that value or boolean false if it has gone past the start of the array;
  - reset($arr) - sets the pointer to the starts of the array then returns that value or false if the aray is empty.

These are the basic navigation functions of PHP which work well with either indexed or associative arrays. In our next tutorial we look at more associative array friendly functions.

Top of Page  Tutorials Home  PHP References  PHP Books
©Imagenation 2000-2004