How can I remove duplicate values from an array in PHP?
php
arrays
duplicate-data
Answers
2
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;
else
$duplicate_keys[] = $key;
}
foreach ($duplicate_keys as $key)
unset($array[$key]);
return $keep_key_assoc ? $array : array_values($array);
}
Saturday, September 24, 2022
3
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
3
Bit late, but may help someone looking for same answer. I used this very simple approach to;
- remove all the keys from nested arrays that contain no value, then
- remove all the empty nested arrays.
$postArr = array_map('array_filter', $postArr);
$postArr = array_filter( $postArr );
Wednesday, August 17, 2022
1
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)) {
continue;
}
// Note that we have seen this article
$seen[$row['fk_article_id']] = NULL;
// Do whatever with your row
var_dump($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 :
php
arrays
duplicate-data
Use array_unique().
Example: