Removing Array Elements

You want to remove one or more elements from an array.

To delete one element, use unset():

unset($fruits[2]); unset($fruits['red']);
To delete multiple noncontiguous elements, also use unset():
unset($fruits[1], $fruits[3]); unset($fruits['red'], $fruits['orange']);
To delete multiple contiguous elements, also use array_splice(). It reindexes arrays to avoid leaving holes:
array_splice($fruits, $offset, $length)
Use array_shift() to remove the first element. Use array_pop() to remove the last element

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
echo "<p><b>Use array() to create the array fruits.</b></p>";
$fruits = array('Apples', 'Grapes', 'Bananas', 'Oranges', 'Pears', 'Dates');
// use print_r() to print the array
print_r($fruits);
echo "<br />the array size is: ", count($fruits);

// unset($fruits[1])
echo "<p><b>unset($fruits[1]).</b></p>";
unset($fruits[1]);
print_r($fruits);
echo "<br />the array size is: ", count($fruits);

// add new element
echo "<p><b>Add new element.</b></p>";
$fruits[] = "Kiwis";
print_r($fruits);
echo "<br />the array size is: ", count($fruits);

// assign blank
echo "<p><b>Assign blank to 3rd element.</b></p>";
$fruits[2] = '';
print_r($fruits);
echo "<br />the array size is: ", count($fruits);

// to compact the array into a densely filled numeric array, use array_values():
echo "<p><b>Compact the array into a densely filled numeric array</b></p>";
$fruits = array_values($fruits);
print_r($fruits);
echo "<br />the array size is: ", count($fruits);

// array_splice() automatically reindexes arrays to avoid leaving holes
echo "<p><b>Using array_splice() to remove 3rd and 4th elements</b></p>";
$fruits = array('Apples', 'Grapes', 'Bananas', 'Oranges', 'Pears', 'Dates');
array_splice($fruits, 2, 2);
print_r($fruits);
echo "<br />the array size is: ", count($fruits);

// array_shift() removes the first element
echo "<p><b>Using array_shift() to remove the first element</b></p>";
$fruits = array('Apples', 'Grapes', 'Bananas', 'Oranges', 'Pears', 'Dates');
array_shift($fruits);
print_r($fruits);
echo "<br />the array size is: ", count($fruits);

// array_pop() removes the last element
echo "<p><b>Using array_pop() to remove the last element</b></p>";
array_pop($fruits);
print_r($fruits);
echo "<br />the array size is: ", count($fruits);
?>
</p>
</body>
</html>

View the effect


Arrays | What is an array? | Creating Arrays | Iterating | Not Beginning at 0 | Initializing to a Range | Modifying | Removing Elements | Removing Duplicate | Changing Size | Key in an Array | Element in an Array | Position of a Value | Largest or Smallest Element | Reversing | Randomizing
© 2008: Hann So
email: hso@voyager.deanza.edu