␡
- Listing of String Functions
- Using the String Functions
- Formatting Strings
- Converting to and from Strings
- Creating Arrays
- Modifying Arrays
- Removing Array Elements
- Looping Over Arrays
- Listing of the Array Functions
- Sorting Arrays
- Navigating through Arrays
- Imploding and Exploding Arrays
- Extracting Variables from Arrays
- Merging and Splitting Arrays
- Comparing Arrays
- Manipulating the Data in Arrays
- Creating Multidimensional Arrays
- Looping Over Multidimensional Arrays
- Using the Array Operators
- Summary
This chapter is from the book
Removing Array Elements
Another way of modifying arrays is to remove elements from them. To remove an element, you might try setting an array element to an empty string, "", like this:
<?php $fruits[0] = "pineapple"; $fruits[1] = "pomegranate"; $fruits[2] = "tangerine"; $fruits[1] = ""; for ($index = 0; $index < count($fruits); $index++){ echo $fruits[$index], "\n"; } ?>
But that doesn't remove the element; it only stores a blank in it:
pineapple tangerine
To remove an element from an array, use the unset function:
unset($values[3]);
This actually removes the element $values[3]. Here's how that might work in our example:
<?php $fruits[0] = "pineapple"; $fruits[1] = "pomegranate"; $fruits[2] = "tangerine"; unset($fruits[1]); for ($index = 0; $index < count($fruits); $index++){ echo $fruits[$index], "\n"; } ?>
Now when you try to display the element that's been unset, you'll get a warning:
pineapple PHP Notice: Undefined offset: 1 in C:\php\t.php on line 8