PHP tutorials
How do you access the elements of an Array?
How do you ‘access’ the elements of an array?
Answer:
Technique 1 - A simple for loop
This technique can be used only for arrays that are zero based, i.e. where you haven’t specified a value for the key. If you have specified keys for your array, then you'll need to use either Technique 2 or Technique 3.
<?php
$busy_period = array('May', 'June', 'July');
//display the individual elements of the array
for($i = 0; $i < sizeof($busy_period); $i++)
{
echo '<br />' . $busy_period[$i];
}
//Remove the array from memory
unset($busy_period);
?>
Output
May June July
Technique 2 - A simple foreach loop
This technique uses the special foreach loop which cycles through each element of the array. This is the most common technique for cycling through elements of an array because the foreach loop works with any kind of index values.
<?php
$busy_period = array(5 => 'May', 6 => 'June', 7 => 'July');
//display the individual elements of the array
foreach($busy_period as $key => $value)
{
echo '<br />Key Value: ' . $key . ' element value: ' . $value;
}
//Remove the array from memory
unset($busy_period);
?>
Output
Key Value: 5 element value: May Key Value: 6 element value: June Key Value: 7 element value: July
Technique 3 - A for loop with key, current and next array functions
This technique shows how to use a standard for loop on an array that is not zero indexed based. It uses the key, current and next functions to retrieve the key, current array element value and move the pointer to the next element in the array.
<?php
$busy_period = array(5 => 'May', 6 => 'June', 7 => 'July');
//display the individual elements of the array
for($i = 0; $i < sizeof($busy_period); $i++)
{
$month_number = key($busy_period); //get the key value (e.g. 5)
$month_name = current($busy_period); //get the element value (e.g. ‘May’)
echo '<br />Key Value: ' . $month_number . ' element value: ' . $month_name;
next($busy_period); //move to the next array element.
}
//Remove the array from memory
unset($busy_period);
?>
Output
Key Value: 5 element value: May Key Value: 6 element value: June Key Value: 7 element value: July
PHP Reference Manual
array - Creates an array variable
current - The value of the current element in the array
foreach - Loop through each element of an array
key - The key of the current element in the array
next - Increments pointer to next element in the array
sizeof - Find the number of elements in an Array
unset - Deletes a variable
Arrays
Adding Elements to an Array
Learn the different techniques of adding elements to an array, and see how they can
be used in PHP scripts
Adding Elements to an array with a keyed index
Learn how to add elements to an array that have a key index, or
where you need to specify one.
Comments or questions relating to this article have been disabled. They will be back soon.
Copyright
Let notice be given that this is copyright information