PHP – Remove duplicate values from array
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:
- <?php
- // duplicate values: 3, mpp
- $aray = array(3, ‘abc’, 3, ‘mpp’, 33, ‘mpp’, 8);
- $aray = array_unique($aray);
- // test
- print_r($aray); // Array ( [0] => 3 [1] => abc [3] => mpp [4] => 33 [6] => 8 )
- ?>
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:
- <?php
- // duplicate values: 122, mpp
- $aray = array(122, ‘abc’, ’122′, ‘mpp’, 33, ‘mpp’);
- $aray = array_unique($aray);
- // test
- print_r($aray); // Array ( [0] => 122 [1] => abc [3] => mpp [4] => 33 )
- ?>
Follow @phpzag
