Changes

PHP Arrays

1,585 bytes added, 18:13, 1 June 2007
Using Array Pointers
The first element is Red
The next element is Yellow
</pre>
 
== Changing, Adding and Removing Array Elements ==
 
An array element can be changed by assigning a new value to using the appropriate index key. For example to change teh firsty element of an array:
 
<pre>
$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");
 
$colorArray[0] = "Orange";
</pre>
 
A new item can be added to the end of an array using the ''array_push()'' function. This function takes two arguments, the first being the name of the array and the second the value to be added:
 
<pre>
$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");
 
array_push($colorArray, "White");
</pre>
 
A new element can be inserted at the start of the array using the ''array_shift()'' function which takes the array anem and the value to be added as arguments:
 
<pre>
$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");
 
array_shift($colorArray, "White"); // Add White to start of array
</pre>
 
The last item added to an array can be removed from the array using the array_pop() function. The following example removes the last element added:
 
<pre>
$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");
 
array_push($colorArray, "White"); // Add White to end of array
 
array_pop($colorArray); // Remove White from the end of teh array
</pre>
 
The first item in the array can be removed using the ''array_unshift()'' function:
 
<pre>
$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");
 
array_shift($colorArray, "White"); // Add White to start of array
 
array_unshift($colorArray) // Remove White from the start of the array
</pre>