Arrays in PHP

An Array is a list variable that can store and index multiple values. An array is useful when the data you want to store has something in common or is logically grouped into a set

you can create an array using array() function, this function have one or more arguments, Let's define an array called $animals and assign four strings to it:

$users = array ("cat", "dog", "fish", "rabbit" );

echo $array[0]; //returns "cat"
echo $array[1]; //returns "dog"
echo $array[2]; //returns "fish"
echo $array[3]; //returns "rabbit"

Now each item of the array is accessed using the variable name, followed directly by square brackets containing the number of the item to be accessed. The number listing of the array starts at zero, so the first item is 0, second is 1, third is 2, etc.

Array looping
If you want to store multiple values in array, it will takes you quite some time to type in one by one. Instead of typing it, you can use 'foreach' statement to loop all the value within an array.

<?php
$animals= array("dog", "cat", "goat");
foreach($animals as $key => $value) {
echo $key . " " . $value . "<br>";
}
?>
And the result will be
0 dog
1 cat
2 goat

Bookmark This Page

Link Partners