PHP Arrays

Array is a special variable, which can hold more than one value at a time. This is a more convenience way to handle a collection of defined data and we often use a loop to access array data.

Example

<?php
$state = array("Anambra", "Lagos", "Kaduna", "Edo");
?>


Accessing Array Value

Note: an array index is the way we access array values, and this index numbering start from 0 and not 1, therefore the $state array we created has 4 elements with their index as follows (Anambra[0], Lagos[1], Kaduna[2], Edo[3]

Example

<?php
$state = array("Anambra", "Lagos", "Kaduna", "Edo");
echo "I visited ". $state[0]." and ". $state[2];
print "<br/>";
echo count($state);
?>

Output

I visited Anambra and Kaduna

count function

Using the count function tells us the length (number of elements) of an array
<?php $state = array("Anambra", "Lagos", "Kaduna", "Edo");
echo count($state);
?>

Output

4

Looping through all Array Value

Note: I appended the break line tag <br/> so that each array value can appear on separate line.

Example

<?php
$state = array("Anambra", "Lagos", "Kaduna", "Edo");
$array_len = count($state);
for($i=0; $i<$array_len; $i++){
  print $state[$i]."<br/>";
}
?>

Output

Anambra
Lagos
Kaduna
Edo




Next »


Home    |    Learn Programming   |    Learning Management System   |    Computer Based Testing System    |    Contact Us