Remove duplicated values completely deleted from array in php

坚强是说给别人听的谎言 提交于 2019-12-23 02:42:24

问题


I want to remove the values from array which are same. For example: This is the array.

Array ( [0] => 1 [1] => 63 [2] => 1 )

is there any function or something in core php which return me only the value which is not duplicate i.e value with index number 1 and delete index 0 and 2, I want the result

Array ( [1] => 63) 

Is there any way?


回答1:


You can use array_filter() and array_count_values() to check the count is not greater then 1.

<?php
$data = [1, 63, 1];

$data = array_filter($data, function ($value) use ($data) {
    return !(array_count_values($data)[$value] > 1);
});

print_r($data);

https://3v4l.org/uIVLN

Result:

Array
(
    [1] => 63
)

Will also work fine with multiple dupes: https://3v4l.org/eJSTY




回答2:


One option is to use array_count_values to count the values. Loop and push only the 1 values

$arr = array(1,63,1);
$arrKey = array_flip( $arr ); //Store the key

$result = array();  
foreach( array_count_values($arr) as $k => $v ) {
    if ( $v === 1 ) $result[ $arrKey[$k] ] = $k;
}

echo "<pre>";
print_r( $result );
echo "</pre>";

This will result to:

Array
(
    [1] => 63
)

Doc: array_count_values




回答3:


I believe that the best solution is the following:

function removeDuplicates(array $initialArray) : array 
{
    // Remove duplicate values from an array
    $uniqueValues = array_unique($initialArray);

    // Computes the difference of arrays with additional index check
    $duplicateValues = array_diff_assoc($initialArray, $uniqueValues);

    // Removed any values in both arrays
    return array_diff($uniqueValues, $duplicateValues);
}

This solution utilises the following functions in PHP:

array_unique

array_diff_asoc

array_diff




回答4:


You can use array_keys() with a search value as the second parameter to see how many times a value exists.

$array = [1, 63, 1, 12, 64, 12];

$new = [];
foreach ($array as $value) {
    // Get all keys that have this value. If there's only one, save it.
    if (count(array_keys($array, $value)) == 1) {
        $new[] = $value;
    }
}

Demo: https://3v4l.org/G1DCg

I don't know the performance of this compared to the other answers. I leave the profiling to someone else.



来源:https://stackoverflow.com/questions/49857246/remove-duplicated-values-completely-deleted-from-array-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!