Stripping out duplicate values

array array_unique ( array input)

Consider if the $toppings2 array had been declared like this:

$toppings2 = array("Peppers", "Ham", "Cheese", "Peppers");

In this situation, there'd be two Peppers elements in there, in which case we would want to strip out the duplicate Peppers before running the merges and intersects. This is done by using array_unique(), which takes an array as its parameter and returns the same array with its duplicate values removed, like this:

$toppings2 = array_unique($toppings2);

Try the example code again, this time removing the duplicate Cheese values from $bothtoppings.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Filtering your array through a function >>

Previous chapter: Chopping and changing arrays

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.