What Is An Array?: PHP Arrays
What Is An Array?: PHP Arrays
PHP Arrays
What is an Array?
A variable is a storage area holding a number or text. The problem is, a variable will hold only
one value.
An array is a special variable, which can store multiple values in one single variable.
Numeric Arrays
A numeric array stores each array element with a numeric index.
1. In the following example the index are automatically assigned (the index starts at 0):
$cars=array("Saab","Volvo","BMW","Toyota");
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
Example
In the following example you access the variable values by referring to the array name and
index:
<?php
$cars[0]="Saab";
2
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
echo $cars[0] . " and " . $cars[1] . " are Swedish cars.";
?>
Associative Arrays
An associative array, each ID key is associated with a value.
When storing data about specific named values, a numerical array is not always the best way to
do it.
With associative arrays we can use the values as keys and assign values to them.
Example 1
Example 2
This example is the same as example 1, but shows a different way of creating the array:
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
<?php
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
?>
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
$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] => Arra (
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array(
[0] => Glenn
)
[Brown] => Array(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
4
Example 2
array() creates an array, with keys and values. If you skip the keys when you specify an array, an
integer key is generated, starting at 0 and increases by 1 for each value.
Syntax
array(key => value)
Example 1
<?php
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");
print_r($a);
?>
Array ( [a] => Dog [b] => Cat [c] => Horse )
Example 2
<?php
$a=array("Dog","Cat","Horse");
print_r($a);
?>
Array ( [0] => Dog [1] => Cat [2] => Horse )