Sunday, March 20, 2011

Remove duplicate values in array and reindexing - php.



You have an array that contain duplicates value, but you don't want any duplication. The best way to remove duplicates value in array is by used array_unique() function. Let say you have an array $your_array;

$your_array = Array ( [0] => 2 [1] => 4 [2] => 4 [3] => 4 [4] => 5 [5] => 6)

In that array, element in index 1,2 and 3 have same value which is 4. You want to remove this duplicate values. You need to used array_unique().
array_unique($your_array);
array_unique() only remove duplicates value but the index of array is maintain. Your array will be like this;
Array ( [0] => 2 [1] => 4 [4] => 5 [5] => 6 )
You need to reset the index in array. To reset the index, you need to use foreach() function.
Before that, you need to create a variable that hold a value to represent the new index in array. Let say the variable is;

$new_index=0;
$new_index will be used in foreach() function. This value will be increased and replaced with the index value of array.
$new_index=0;
foreach($your_array as $key=>$value){
    $your_array_new[$new_index]=$value;
    $new_index++;
}//foreach


This will reset the index in array. Your array will be like this;
Array ( [0] => 2 [1] => 4 [2] => 5 [3] => 6 )

No comments:

Related Posts Plugin for WordPress, Blogger...