Find the Non-Repeating Elements in an Array

后端 未结 4 1866
别跟我提以往
别跟我提以往 2021-01-23 04:24

My array is :

$array= array(4,3,4,3,1,2,1);

And I\'d like to output it like below:

Output = 2 

(As 2 i

4条回答
  •  Happy的楠姐
    2021-01-23 05:03

    You could use the array_count_values() php function.

    For example :

    $numbers = [4, 3, 4, 3, 1, 2, 1];
    
    // build count array as key = number and value = count
    $counter_numbers = array_count_values($numbers);
    
    print_r($counter_numbers);
    

    Output :

    Array
    (
        [4] => 2
        [3] => 2
        [1] => 2
        [2] => 1
    )
    

    Then loop through the new array to get non-repeated values :

    $unique_numbers = [];
    
    foreach ($counter_numbers as $number => $count) {
        if ($count === 1) {
            $unique_numbers[] = $number;
        }
    }
    
    print_r($unique_numbers);
    

    Output :

    Array
    (
        [0] => 2
    )
    

    Hope it helps.

提交回复
热议问题