phparraysfilteringunique

Separate flat array values into an array of unique values and an array of duplicate values


I want to find unique values. I don't want to array format, I want only string.

<?php
$array = array("kani","yuvi","raja","kani","mahi","yuvi") ;
$unique_array = array(); // unique array
$duplicate_array = array(); // duplicate array
foreach ($array as $key => $value) {
  if (!in_array($value,$unique_array)) {
       $unique_array[$key] = $value;
  } else {
     $duplicate_array[$key] = $value;
  }
}
echo "unique values are:-<br/>";
echo "<pre/>";print_r($unique_array);

echo "duplicate values are:-<br/>";
echo "<pre/>";print_r($duplicate_array);

Solution

  • You can use array_unique() in single line like below:-

    <?php
    
    $unique_array = array_unique($array); // get unique value from initial array
    
    echo "<pre/>";print_r($unique_array); // print unique values array
    ?>
    

    Output:- https://eval.in/601260

    Reference:- http://php.net/manual/en/function.array-unique.php

    If you want in string format:-

    echo implode(',',$final_array);
    

    Output:-https://eval.in/601261

    The way you want is here:-

    https://eval.in/601263

    OR

    https://eval.in/601279