So Arrays Huh

Temporary storage of information

Before getting started on the actual content, it might help to have some idea of what an array actually is. To bring it technically, one could say that an array is a data structure consisting of a group of elements that are accessed by indexing. In practice it means that you have one variable (the array) which contains a series of values, which can be accessed through an index, the key.

Right.. now back to the arrays. How do you create them? Use them?

Creating an array is extremely simple. You just define them like this:

1
2
3
<?php
 $MyArray = array();
 ?>
<?php
 $MyArray = array();
 ?>

Naturally, that is not all. You want to add some values to the array. And you would like manipulate and and use these values. How do you go about this?

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
 // First create an array, filled with three values:
 $MyArray = array();
 $MyArray[0] = 'beet';
 $MyArray[1] =  'potatoe';
 $MyArray[2] = 'lettuce';
 
 // An other way would be:
 $MyArray = array(0=>'beet', 1=>'potatoe', 2=>'lettuce'); 
 
// or even:
$MyArray = array('beet','potatoe','lettuce'); 
?>
<?php
 // First create an array, filled with three values:
 $MyArray = array();
 $MyArray[0] = 'beet';
 $MyArray[1] =  'potatoe';
 $MyArray[2] = 'lettuce';
 
 // An other way would be:
 $MyArray = array(0=>'beet', 1=>'potatoe', 2=>'lettuce'); 

// or even:
$MyArray = array('beet','potatoe','lettuce'); 
?>

Now we have created one array with 3 elements, beet; potatoe and lettuce. They can be accessed through the keys 0; 1 and 2. An example might help. In the example, note the use of print_r, which will give an overview of the structure of the array:

1
2
3
4
5
6
7
8
<?php
 echo $MyArray[0];
 
 // results in array:
 print_r($MyArray);
 
 // results in array( [0] => 'beet', [1] => 'potatoe', [2] => 'lettuce');
 ?>
<?php
 echo $MyArray[0];
 
 // results in array:
 print_r($MyArray);
 
 // results in array( [0] => 'beet', [1] => 'potatoe', [2] => 'lettuce');
 ?>

You could decide that you wanted to use a word as a key:

1
2
3
4
5
<?php
 $fruit = array();
 $fruit['strawberry'] = array();
 $fruitx['strawberry']['color'] = 'Red with seeds on the skin';
 ?>
<?php
 $fruit = array();
 $fruit['strawberry'] = array();
 $fruitx['strawberry']['color'] = 'Red with seeds on the skin';
 ?>

And you can test whether a specific key exists using array_key_exists:

1
2
3
4
5
6
7
8
9
10
11
<?php
 $myfruit = 'strawberry';
 if(array_key_exists($myfruit, $fruit))
   {
   echo $fruit[$myfruit]['color'];
   }
 else
   {
   echo "We do not know the color of ".$myfruit.".";
   }
 ?>
<?php
 $myfruit = 'strawberry';
 if(array_key_exists($myfruit, $fruit))
   {
   echo $fruit[$myfruit]['color'];
   }
 else
   {
   echo "We do not know the color of ".$myfruit.".";
   }
 ?>

This primer should get you startet with arrays in PhP. Please let me know if you have any suggestions or questions.

Leave a Reply