How can I remove duplicate values from an array in PHP?
Use array_values(array_unique($array));
array_unique
: for unique array
array_values
: for reindexing
if (@!in_array($classified->category,$arr)){
$arr[] = $classified->category;
?>
<?php } endwhile; wp_reset_query(); ?>
first time check value in array and found same value ignore it
$arrDuplicate = array ("","",1,3,"",5);
foreach(array_unique($arrDuplicate) as $v){
if($v != "" ){$arrRemoved = $v; }}
print_r($arrRemoved);
function arrayUnique($myArray)
{
$newArray = Array();
if (is_array($myArray))
{
foreach($myArray as $key=>$val)
{
if (is_array($val))
{
$val2 = arrayUnique($val);
}
else
{
$val2 = $val;
$newArray=array_unique($myArray);
$newArray=deleteEmpty($newArray);
break;
}
if (!empty($val2))
{
$newArray[$key] = $val2;
}
}
}
return ($newArray);
}
function deleteEmpty($myArray)
{
$retArray= Array();
foreach($myArray as $key=>$val)
{
if (($key<>"") && ($val<>""))
{
$retArray[$key] = $val;
}
}
return $retArray;
}
explode(",", implode(",", array_unique(explode(",", $YOUR_ARRAY))));
This will take care of key associations and serialize the keys for the resulting new array :-)
An alternative for array_unique() function..
Using Brute force algorithm
//[1] This our array with duplicated items
$matches = ["jorge","melvin","chelsy","melvin","jorge","smith"];
//[2] Container for the new array without any duplicated items
$arr = [];
//[3] get the length of the duplicated array and set it to the var len to be use for for loop
$len = count($matches);
//[4] If matches array key($i) current loop Iteration is not available in //[4] the array $arr then push the current iteration key value of the matches[$i] //[4] to the array arr.
for($i=0;$i
if(array_search($matches[$i], $arr) === false){ array_push($arr,$matches[$i]); } } //print the array $arr. print_r($arr); //Result: Array ( [0] => jorge [1] => melvin [2] => chelsy [3] => smith )