Viewed   188 times

How can I remove duplicate values from an array in PHP?



Use array_unique().


$array = array(1, 2, 2, 3);
$array = array_unique($array); // Array is now (1, 2, 3)
Monday, October 3, 2022

try the following code

function my_array_unique($array, $keep_key_assoc = false){
    $duplicate_keys = array();
    $tmp = array();       

    foreach ($array as $key => $val){
        // convert objects to arrays, in_array() does not support objects
        if (is_object($val))
            $val = (array)$val;

        if (!in_array($val, $tmp))
            $tmp[] = $val;
            $duplicate_keys[] = $key;

    foreach ($duplicate_keys as $key)

    return $keep_key_assoc ? $array : array_values($array);
Saturday, September 24, 2022

Consider first splitting the keywords argument by spaces, then finding the unique values:

$posted = array_unique(explode(' ', str_replace("n", ' ', $posted)));
Tuesday, December 27, 2022

Bit late, but may help someone looking for same answer. I used this very simple approach to;

  1. remove all the keys from nested arrays that contain no value, then
  2. remove all the empty nested arrays.

$postArr = array_map('array_filter', $postArr);
$postArr = array_filter( $postArr );
Wednesday, August 17, 2022

A quick way using array_reduce would look like:

$unique = array_reduce($subject, function($final, $article){
    static $seen = array();
    if ( ! array_key_exists($article['fk_article_id'], $seen)) {
        $seen[$article['fk_article_id']] = NULL;
        $final[] = $article;
    return $final;

Try a working example.

Edit: Seems you don't want to work with the aggregated results. Here are two other thoughts:

Filtering in PHP

$seen = array();
while ($row = pg_fetch_assoc($authors_result)) {
    // Skip this row if we have already seen its article id
    if (array_key_exists($row['fk_article_id'], $seen)) {
    // Note that we have seen this article
    $seen[$row['fk_article_id']] = NULL;
    // Do whatever with your row

Filtering in the DB

The idea here is to change the query being executed so that the repeated article ids do not appear in the result set. How this is done will depend on the query that you're already using.

Thursday, October 13, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :