PHP arrays

An array always starts at location 0. i.e. Array[0].

To create an array, we must tell the PHP that which variable is an "array variable". So declare the variable as an array before you can use that variable as an array.

Declaration method:

$colours = array ("white", "red","blue","green");


Example 1:

<?php
$films = array ("The Little Mermaid","Snow White","Cinderella");
//Comment: Adding 2 more entries to the array
$films[ ] ="Toy Stories";
$films[ ]="Wall E";
echo "$films[3]";
?>

Example 2:
(To count the number of arrays)

<?php
$films = array ("The Little Mermaid","Snow White","Cinderella");
$array_length= count($films);
echo "$array_length";
?>


Example 3:
(To loop only the number of arrays available)

<?php
$films = array ("The Little Mermaid","Snow White","Cinderella");
$array_length= count($films);
echo "$array_length <br >";
echo "The films are: <br>";
for ($counter=0; $counter < $array_length; $counter++)
{
echo "$films[$counter] <br>";
}
?>


Example 4:
(To loop only the number of arrays available more efficiently)

<?php
$films = array ("The Little Mermaid","Snow White","Cinderella");
$array_length= count($films);
echo "$array_length <br >";
echo "The films are: <br>";
while (list(, $value) = each ($films))
{
echo "Value: $value<br>";
}
?>

Example 5:
(Count the number of apples in the fruit list)

<?php
$fruit_list=array("apple","pear","apple","orange","starfruit","apple");
while (list (, $value) = each ($fruit_list))
{
$count++;
if($value == "apple")
{
$apple_count++;
}
}
echo "There are $apple_count apples.<br> The array has $count elements";
?>