Modifying arrays in PHP

Sep 17, 2009 Author: Developer

Arrays can be changed at any time in the script, just as variables can. The individual values can be changed, elements can be added or removed, and elements can be rearranged. For example, if you have an existing array named $capitals, you can use the following statement to change the value of an element:

$capitals[‘TX’] = “Big Springs”;

This statement changes the value of this element of the $capitals array, although the people in Austin might object to the change. Or you could use the following statement:

$capitals[‘RI’] = “Providence”
; The statement adds a new element to the array, leaving the existing elements intact. Suppose that your array has numbers for keys, as is the case with the following array, which is created at the beginning of a script:

$customers[1] = Sam Smith
$customers[2] = Sue Jones
$customers[3] = Mary Huang

You can use the following statement later in the script:

 $customers[] = “Juan Lopez”
$customers now becomes an array with four elements, as follows:


$customers[1] = Sam Smith
$customers[2] = Sue Jones
$customers[3] = Mary Huang
$customers[4] = Juan Lopez

You can also copy an entire existing array into a new array with this statement:

$customerCopy = $customers;

views 4279
  1. Add New Comment