PHP Array

Subject: Web development using PHP and MySQL
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 1

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


Accessing Array Value with index
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 2

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

Output:
I visited Anambra and Kaduna

Count function
Using the count function tells us the length (number of elements) of an array.

Example 3

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

Output:
4

Looping through all Array Value
Note: I appended the break line tag
so that each array value can appear on separate line.

Example 4

<?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

By: Benjamin Onuorah

Comments

No Comment yet!

Login to comment or ask question on this topic


Previous Topic Next Topic

Supported by