PHP's World Of Arrays

Arrays in PHP are quite powerful, partly because they are not actually arrays (read on for an explanation), but can be treated as such when needed. They gain most of the utility from a vast library of built in helper functions associated with them.

Much of my day is spent looking at others code, (were ‘others’ does include ‘me in the past’), and I often see arrays under utilized or code that fights arrays by implementing foreach loops where a single function call would suffice. With some review of the functionality afforded arrays in PHP you can learn to use them more effectively and realize that they may very well be the best solution in circumstances you had not thought of before. This is nothing against Object Oriented Programming, as I consider myself a OO programmer. There is just quite a bit that can be done efficiently and elegantly with plain old arrays in PHP.

So as a refresher course for myself and hopefully to show others some array functionality they were not aware existed, I’ve decided to write a few blog posts on some things I find useful (and have newly discovered after re-reading the array docs).

This being the first of those posts, I’ll start with the basics, a very quick intro to just what an array is and then cover examples of using arrays as some of the more simple data structures in computer science: Stacks and Queues.

What Is An Array In PHP?

What is referred to as an ‘array’ in PHP is actually an ordered map. The keys of an array can be either an integer or a string. The value for an array element can be anything.

Arrays can be created using the array() construct or in a more literal fashion of using brackets ([ ])

$x = array('bob');
$x = array(0 => 'bob');
$x[] = 'bob';
$x[0] = 'bob';

All the examples above will result in this array:

array(0 => 'bob')

If a key is not specified for a value, a new key is created with the value of 1 + the current max of the integer keys in the array.

$y = array(0 => 'red', 1 => 'blue', 7 => 'green');
$y[] = 'brown';

The $y array would now be:

$y = array(0 => 'red', 1 => 'blue', 7 => 'green', 8 => 'brown');

For more of the basics of PHP arrays, there is an excellent php.net page devoted to that subject.

Using Arrays For Basic Data Structures

Stacks

In computer science, a Stack is a last in, first out (LIFO) structure.

>push     pop>
     \   /
       X
       X
       X
       X
       X

An example of a Stack is your browser history. You click a link and it is pushed onto the top of your browser history. You continue to click links and they are continually pushed onto the top of that Stack. Then when you click on the ‘back’ button, the very top link is popped of your history Stack.

In PHP the functions array_push and array_pop are used for manipulating an array as a Stack.

$browser_history = array('https://mail.google.com', 'http://www.php.net' );
array_push($browser_history, 'http://www.topgear.com/uk/');


print_r($browser_history);

// Array
// (
//     [0] => https://mail.google.com
//     [1] => http://www.php.net
//     [2] => http://www.topgear.com/uk/
// )

$site = array_pop($browser_history);
echo "site: {$site}";

// site: http://www.topgear.com/uk/

print_r($browser_history);

// Array
// (
//     [0] => https://mail.google.com
//     [1] => http://www.php.net
// )

Note that in PHP, rather than using array_push, you can just use bracketed syntax which has the same effect.

array_push($array, 'value')
// has the same effect as
$array[] = 'value';

Queues

A Queue is a First-In-First-Out (FIFO) data structure. (think conveyor belt)

enqueue                  dequeue
(unshift)      queue      (shift)
       X -->  XXXXXXX -->  X

In PHP, you can use an array as a Queue by utilizing array_unshift to prepend and element to the beginning of an array and then array_pop to take an element off the end of the same array.

An example would be any perishable items in your grocery store’s dairy case. As items come into the store they are loaded in the back of the case and customers select items for purchase from the front of the case.

$yogurts = array('exp:05/10/2011', 'exp:05/08/2011' );

print_r($yogurts);

//Array
//(
//  [0] => exp:05/10/2011
//  [1] => exp:05/08/2011
//)

array_unshift($yogurts, 'exp:05/13/2011', 'exp:05/12/2011');

print_r($yogurts);

//Array
//(
//  [0] => exp:05/13/2011
//  [1] => exp:05/12/2011
//  [2] => exp:05/10/2011
//  [3] => exp:05/08/2011
//)

Note, these methods do not return the affected array so you wouldn’t normally do:

$yogurts = array_unshift($yogurts, 'exp:05/13/2011', 'exp:05/12/2011');

as array_pop simply returns the last value of the array and array_unshift returns the new number of elements in the array.

So that is it for now, next up I’ll discuss using the various function to calculate the differences and intersections between array.

Tagged PHP array queue stack

Comments (0)

Add a Comment

Meta