April 24, 2012
Remove duplicated values function
Question by user1345545
function remove_values($arr){
$_a = array();
while(list($key,$val) = each($arr)){
$_a[$val] = 1;
}
return array_keys($_a);
}
i can’t follow the above function well.i don’t know what’s the effect of $_a[$val] = 1;
anyone can explain it to me thank you
Answer by Robin Castlin
Well all this does is to insert the value into the key of an array. Since all keys are unique in an array, you will remove all duplicates.
array_keys()
simply gives back that array in it’s ordinary form.
Example:
$arr = array('red', 'green', 'red');
$arr = remove_values($arr);
gives
array( 'red' => 1,
'green' => 1);
which results in
array('red', 'green');
since “red” can only be a keyvalue once.
Answer by Starx
For the purpose of the function, Why not just use array_unique($array)
?
Like this
function remove_values($arr){
return array_keys(array_unique($arr));
}
Update:
Ok, Since you are trying to learn. Here is the explanation for the function in the post
function remove_values($arr){
$_a = array(); //Creates a temporary array to store matching
while(list($key,$val) = each($arr)){ //till their is item is array, loop it
$_a[$val] = 1; //Store in the temporary array with array's values as index, thus eliminating the duplicates
//^ Here storing with the value as index IS THE KEY
}
return array_keys($_a); //return only the keys, which in fact are the unique values
}