Changes

Jump to: navigation, search

PHP Arrays

1,503 bytes added, 18:27, 1 June 2007
Changing, Adding and Removing PHP Array Elements
array_unshift($colorArray) // Remove White from the start of the array
</pre>
 
== Looping through PHP Array Elements ==
 
It is often necessary to loop through each element of an array to either read or change the values contained therein. There are a number of ways that this can be done.
 
One such mechanism is to use the ''foreach'' loop. The foreach loop works much like a for or while loop and allows you to iterate through each array element. there are two ways to use foreach. The first assigns the value of the current element to a specified variable which can then be acessed in the body of the loop. The syntax for this is:
 
foreach ($arrayName as $variable)
 
For example:
 
<pre>
$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");
 
foreach ($colorArray as $color)
{
echo "$color <br>";
}
</pre>
 
Will result in tyhe following output:
 
<pre>
Red
Yellow
Green
Blue
Indigo
</pre>
 
For associative arrays the foreach command allows you to iterate through both the keys and the values using the following syntax:
 
foreach ($arrayName as $variable)
 
For example:
 
<pre>
$customerArray = array('customerName'=>'John Smith', 'customerAddress'=>'1 The Street', 'accountNumber'=>'123456789');
 
foreach ($customerArray as $key=>$value)
{
echo "Key = $key <br>";
echo "Value = $value <br>";
}
</pre>
 
will result in the following output:
 
<pre>
Key = customerName
Value = John Smith
Key = customerAddress
Value = 1 The Street
Key = accountNumber
Value = 123456789
</pre>

Navigation menu