Saturday 27 June 2015

Remove / Get duplicate array values - Reset array keys in PHP

In this tutorial you can learn How to Remove, and to get duplicate values from array, and to Reset array keys in PHP.

Remove duplicate values from array

To remove duplicate values from an array, use the 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: 1, mp
$aray = array(1, 'abc', 1, 'mp', 33, 'mp', 8);
$aray = array_unique($aray);

// test
print_r($aray);      // Array ( [0] => 1 [1] => abc [3] => mp [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: 12, mp
$aray = array(12, 'abc', '12', 'mp', 33, 'mp');
$aray = array_unique($aray);

// test
print_r($aray);      // Array ( [0] => 12 [1] => abc [3] => mp [4] => 33 )
?>

Get duplicate array elements

If you want to get only the duplicate elements from an array, you can use the following construction:
array_unique(array_diff_assoc($aray, array_unique($aray)));
Example:
<?php
// duplicate values: 12, mp
$aray = array(12, 'abc', '12', 'mp', 33, 'mp', 8);
$duplicates = array_unique(array_diff_assoc($aray, array_unique($aray)));

// test
print_r($duplicates);        // Array ( [2] => 12 [5] => mp )
?>

Reset array keys

PHP has not a function especialy to reset array keys, but it can be used another function to get this result.
To reset (or renumber) the keys of an array you can use array_merge(). This function merges the elements of one or more arrays together. In the result array, the numeric keys will be renumbered, starting from zero.
So, if you add only one array with unordered numeric keys, it will return an array with ordered numeric keys, starting from zero, with the values in the same order.
Example:
<?php
$aray = array(1=>'abc', 5=>23, 12=>'mp');
$aray = array_merge($aray);

// test
print_r($aray);      // Array ( [0] => abc [1] => 23 [2] => mp )
?>

0 comments:

Post a Comment