In Creating Arrays in PHP, you learned how PHP arrays work, and saw how to create an array using PHP.
Now take things further, and look at how to access the individual elements inside a PHP array. You’ll see how to:
- Read element values
- Alter element values
- Add and remove elements in an array
- Output the entire contents of an array
Changing element values
You assign a new value to an array element in the same way as a regular variable:
$myArray[index] = new value;
The following example changes the 3rd element of the array from “Martin Scorsese” to “Woody Allen”:
<?php $directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" ); $directors[2] = "Woody Allen"; ?>
Adding elements
You can add a new element to an array like this:
$myArray[] =
value;
PHP automatically assigns the next available numeric index to the new element. Here’s an example:
<?php $directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" ); $directors[] = "Woody Allen"; // Displays "Woody Allen" echo $directors[4]; ?>
You can also specify an index. If an element with that index already exists in the array, its value is overwritten; otherwise a new element is created with that index:
<?php $directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" ); $directors[4] = "Woody Allen"; // Displays "Woody Allen" echo $directors[4]; $directors[2] = "Ingmar Bergman"; // Displays "Ingmar Bergman" echo $directors[2]; ?>
Removing elements
To remove an element from an array, you call
unset()
, passing in the element to remove. (You can also use unset()
on regular variables to delete them.) Here’s an example:<?php $directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" ); // Displays "Stanley Kubrick" echo $directors[1]; unset( $directors[1] ); // Displays nothing (and generates an "Undefined offset" notice) echo $directors[1]; ?>
note: The last line of code above generates an “Undefined offset” notice, which is a minor error. It means that you’re trying to access an array index that doesn’t exist. Normally, PHP doesn’t display or log notices, but you can change this with the
error_reporting()
function.unset()
doesn’t automatically reindex arrays to “close the gap” in the index numbering. For example, after running the above code, "Martin Scorsese"
still has an index of 2
, and "Fritz Lang"
still has an index of 3
. To reindex the array so that the indices are contiguous again, you can use the array_values()
function. For example:<?php $directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" ); // Displays "Stanley Kubrick" echo $directors[1] . "<br />"; unset( $directors[1] ); $directors = array_values( $directors ); // Displays "Martin Scorsese" echo $directors[1] . "<br />"; ?>
0 comments:
Post a Comment