Working with Arrays in PHP

Arrays are a way of storing multiple related values on an ordered way. To access the elements of an array you have to call them by their index. Lets see an example of an array:

<?php

$arrayex = array(“This “, “is “, “a “, “fast “, “airplane”);

print $arrayex[0]; //prints this

print $arrayex[1]; //prints is

print $arrayex[2]; //prints a

print $arrayex[3]; //prints fast

print $arrayex[4]; //prints airplane

?>

On the above example $arrayex is our array and the number between square brackets is the index. The default starting index is 0 but you can change that if you want. For example if we change the first line above with:

$arrayex = array(1 => “This “, “is “, “a “, “fast “, “airplane”);

the starting index will be 1.

The index can also be a string. If it is a string the array is known as an associative array. For example:

$arrayex = array(“Rivera” => “Mariano “, “Ryan” => “Nolan “, “Clemens” => “Roger “);

print $arrayex[‘Rivera’] .'<br>’; //prints Mariano

print $arrayex[‘Ryan’] .'<br>’; //prints Nolan

print $arrayex[‘Clemens’] .'<br>’; //prints Roger

Rivera, Ryan and Clemens are the indexes, also known as keys. Arrays become even more useful is we make them multidimensional.

$arrayex = array(

“Rivera” => array (“Mariano “, “New York ” , 1996),

“Ryan” => array (“Nolan “, “Houston “, 1994),

“Clemens” => array (“Roger “,”Boston “, 1990),

);

print $arrayex[‘Rivera’][0] .$arrayex[‘Rivera’][1] .$arrayex[‘Rivera’][2] .'<br>’;

//prints Mariano New York 1996

To loop through all the values of an array we can use a foreach loop. When we use a foreach loop the array value is stored on a temporary variable.

$arrayex = array(

“Rivera” => array (“Mariano “, “New York ” , 1996),

“Ryan” => array (“Nolan “, “Houston “, 1994),

“Clemens” => array (“Roger “,”Boston “, 1990),

);

foreach($arrayex[‘Clemens’] as $temp)

{

print “$temp<br>”;

}

In the above example the array value is stored on the temporary variable $temp and then printed.PHP has a very extensive list of array functions, we are going to see examples of two more of them. If you need to know the number of elements on an array you can make use of the count function, and to sort the values you can use the sort function.

$arrayex = array(“blue “, “red “, “yellow “, “magenta “, “purple “); print count ($arrayex).'<br>’;

sort($arrayex);

print $arrayex[0];

print $arrayex[1];

print $arrayex[2];

print $arrayex[3];

print $arrayex[4];

// prints blue magenta purple red yellow

About the Author:Diego Botello