Facebook Page Twitter Page LinkedIn Page
× PHP Tutorial PHP Advanced PHP Resources


Arrays are used to store multiple values in a single variable. In PHP, an array can hold multiple data types.

Create an Array

An array can be created using array() keyword. It can be initialized at the time of creation by specifying all elements of the array within the array() keyword and separated by comma(,) or it can be initialized later by specifying value using index number.

Syntax

//Creating an empty array.
$MyArray = array();  

//Creating an array with initialization.
$MyArray = array(value1, value2, ...); 

//initialization after creation of array
$MyArray[index_number] = value;

Access element of an Array

An element of an Array can be accessed with it's index number. Index number for an Array in PHP starts with 0.

PHP Arrays Indexing

Below mentioned example illustrates on indexing for an Array in PHP.

<?php
//creating an array with 3 elements
$MyArray = array('MON', 'TUE', 'WED');

//Add 4th and 5th elements
$MyArray[3] = 'THU';
$MyArray[4] = 'FRI';

echo "MyArray contains: ";
for ($i = 0; $i < count($MyArray); $i++) {
  echo $MyArray[$i]." ";
}
?>

The output of the above code will be:

MyArray contains: MON TUE WED THU FRI 

Change elements of an Array

Any element of an Array can be changed using its index number and assigning a new value.

<?php
//creating an array with 5 elements
$MyArray = array(10, 20, 30, 40, 50);

//changing the value of element at index=1
$MyArray[1] = 1000;

echo "MyArray contains: ";
for ($i = 0; $i < count($MyArray); $i++) {
  echo $MyArray[$i]." ";
}
?>

The output of the above code will be:

MyArray contains: 10 1000 30 40 50

Loop over an Array

By using for loop, while loop or foreach loop, each elements of an array can be accessed.

For Loop over an Array

In the below example, for loop is used to access all elements of the given array.

<?php
//creating an array with 5 elements
$MyArray = array(10, 20, 30, 40, 50);

echo "MyArray contains: ";
for ($i = 0; $i < count($MyArray); $i++) {
  echo $MyArray[$i]." ";
}
?>

The output of the above code will be:

MyArray contains: 10 20 30 40 50

While Loop over an Array

Similarly, while loop is also be used to access elements of the array.

<?php
//creating an array with 5 elements
$MyArray = array(10, 20, 30, 40, 50);

$i = 0;
echo "MyArray contains: ";
while($i < count($MyArray)) {
  echo $MyArray[$i]." ";
  $i++;
}
?>

The output of the above code will be:

MyArray contains: 10 20 30 40 50

Foreach Loop over an Array

In the below example, foreach loop is used to access all elements of an array.

<?php
//creating an array with 5 elements
$MyArray = array(10, 20, 30, 40, 50);

echo "MyArray contains: ";
foreach ($MyArray as $i) {
  echo $i." ";
}
?>

The output of the above code will be:

MyArray contains: 10 20 30 40 50




5