Removing Duplicate Elements

You want to remove duplicates from an array.

Use array_unique() if the array is already complete. It returns a new array that contains no duplicate values.

<!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
$fruits = array('Apples', 'Grapes', 'Bananas', 'Bananas', 'Apples');
print_r($fruits);
$unique = array_unique($fruits);
echo "<p><b>Use array_unique() to remove the duplicates.</b></p>";
print_r($unique);
?>
</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