PHP Arrays


What is an Array?

An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

$cars1="Saab";
$cars2="Volvo";
$cars3="BMW"; 
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is to use an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.
In PHP, there are three types of arrays:
  • Numeric array - Arrays with numeric index
  • Associative array - Arrays with named keys
  • Multidimensional array - An array containing one or more arrays

PHP Numeric Arrays

There are two ways to create a numeric array:
The index can be assigned automatically (index always starts at 0):
$cars=array("Saab","Volvo","BMW","Toyota");
OR   the index can be assigned manually:
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";

Example


 <?php
$cars=array("Saab","Volvo","BMW","Toyota"); 

echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
OR
<?php
$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?> 

OUTPUT: I like Volvo, BMW and Toyota.

 

 

Associative Arrays

Associative arrays are arrays that use named keys that you assign to them. There are two ways to create an associative array:
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

OR

$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";
The named keys can then be used in a script:

Example

 <?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
OR
<?php
$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";
echo "Peter is " . $age['Peter'] . " years old.";
?>

OUTPUT: Peter is 35 years old.


 

Multidimensional Arrays

In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.

Example

In this example we create a multidimensional array, with automatically assigned ID keys:
$families = array
  (
  "Griffin"=>array
  (
  "Peter",
  "Lois",
  "Megan"
  ),
  "Quagmire"=>array
  (
  "Glenn"
  ),
  "Brown"=>array
  (
  "Cleveland",
  "Loretta",
  "Junior"
  )
  );
The array above would look like this if written to the output:
Array
(
[Griffin] => Array
  (
  [0] => Peter
  [1] => Lois
  [2] => Megan
  )
[Quagmire] => Array
  (
  [0] => Glenn
  )
[Brown] => Array
  (
  [0] => Cleveland
  [1] => Loretta
  [2] => Junior
  )
)

echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?";


OUTPUT: Is Megan a part of the Griffin family?