PHP – Remove duplicate values from array

April 4th, 2012 by Laeeq | No comments

Sometime we need to remove duplicate values from an array. For this we will use PHP function: array_unique(). This function returns a new array removing duplicate values, without changing the key of the remaining elements.

Example:

  1. <?php
  2. // duplicate values: 3, mpp
  3. $aray = array(3, ‘abc’, 3, ‘mpp’, 33, ‘mpp’, 8);
  4. $aray = array_unique($aray);
  5. // test
  6. print_r($aray); // Array ( [0] => 3 [1] => abc [3] => mpp [4] => 33 [6] => 8 )
  7. ?>

array_unique() treats the values as string, so, if the array contains for example: 12 (integer), and ’12′ (string), the function keeps only the first value.

Example:

  1. <?php
  2. // duplicate values: 122, mpp
  3. $aray = array(122, ‘abc’, ’122′, ‘mpp’, 33, ‘mpp’);
  4. $aray = array_unique($aray);
  5. // test
  6. print_r($aray);  // Array ( [0] => 122 [1] => abc [3] => mpp [4] => 33 )
  7. ?>

You can subscribe to PHPZAG.COM posts by Email

 

Related Topics:

  • Wrapping Text using PHP
  • PHP 5.5 beta 4 is now available
  • Swapping Array Keys and Values
  • PHP Security
  • Working with Image Metadata in PHP
  • Converting Between Relative and Absolute File Path
  • Parsing File Paths with PHP
  • How to remove HTML Comments with PHP?
  • How to access .htaccess values?
  • Dealing With Common PHP Errors
  • Interview Questions and Answers for Freshers
  • Display numbers with ordinal suffix using PHP
  • Function to set COLLATION on database fields of Mysql
  • Read and write to remote files using PHP
  • Sharing PHP SESSION Variables between Multiple Subdomains
  • PHP 5.5.0 Alpha4 Development Preview Released
  • Check a string starts with http using PHP
  • Cross-Site Scripting Attacks (XSS)
  • PHP 5.4.11 and PHP 5.3.21 released!
  • PHP Memory Leak Issue
  •  

     

    1. No comments yet.
    1. No trackbacks yet.