PHP Tutorial: Arrays mapping your mind in PHP

According to the PHP manual:

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

Uh…. ok, so what does that all mean? Well I’ll start with the part where it said “associates values to keys.” As you should already know all variables in PHP must have a value, whether it is NULL, empty, an array, an integer, whatever. So in the case of an array inside the array there are keys, these keys are like identifiers for the values contained in the array. Here is an example:

<?php
$variable = array('key'=>'value');
?>

So to explain the above code: the variable named $variable is an array, it has one key=>value pair, the key is key and the value is value. So, to use this new value we would simply make a call like this:

echo $variable['key'];

The names of keys can be integers, or strings. If you do not set a key, PHP will set one for you. For example:

<?php
/* PHP will automatically set the key for the value Apples to 0 */
$fruit = array('Apples');
 
/* another way to assign values into an array is like this: */
$veggies[] = 'Lettuce';
$veggies[1] = 'Broccoli';
 
/* so $veggies contains two key=>value pairs, one is 0=>'Lettuce', 
                                    and the other is 1=>'Broccoli' 
To use these values, we can simply do an echo, like this: */
echo "I like to eat {$veggies[0]} and {$veggies[1]} with every meal.";
?>

Now, keys don’t always have to be one or the other, you and mix and match all you’d like:

<?php
$breads[1] = 'Whole Wheat';
$breads['one'] = 'Light Rye';
?>

So there you have it, a simple and straight-forward look at arrays in PHP. I hope you found it useful!

Author: Mike on March 26, 2011
Category: PHP, Tutorials
Tags: , , , ,

One thought on “PHP Tutorial: Arrays mapping your mind in PHP”

  1. Bettie says:

    Hey, subtle must be your middle name. Great post!

Comments are closed.

Last articles