在数组中查找非重复元素

时间:2017-03-25 10:48:26

标签: php arrays

我的数组是:

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

我想输出如下:

Output = 2 

(因为2只出现一次)

4 个答案:

答案 0 :(得分:3)

没有循环的单行:(Demo

var_export(array_keys(array_intersect(array_count_values($array),[1])));

细分:

array_keys(                          // return the remaining keys from array_count_values 
    array_intersect(                 // filter the first array by second
        array_count_values($array),  // count number of occurrences of each value
        [1]                          // identify the number of occurrences to keep
    )
)

如果您(或任何未来的读者)想要保留更多值,请替换array_intersect()中的第二个参数/数组。 例如: 你想保留1,2和3:array(1,2,3)[1,2,3]

P.S。对于记录,您可以将array_filter()与自定义函数一起使用以省略所有非1计数值,但我使用了array_intersect(),因为语法更简洁,IMO更易于阅读。

答案 1 :(得分:2)

您可以使用array_count_values() php函数。

例如:

$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);

输出:

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

然后遍历新数组以获得非重复值:

$unique_numbers = [];

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

print_r($unique_numbers);

输出:

Array
(
    [0] => 2
)

希望它有所帮助。

答案 2 :(得分:0)

你可以这样做:

public function index()
    {
        date_default_timezone_set('Africa/Accra');    // This was to cater for an error given to me earlier
        $this->config->load('email', TRUE);//load email config file
        $confiuration = $this->config->item('mail', 'email');//email configuration

        $this->load->library('email');
        $this->email->initialize($configuration);//initializes email configuration

        $this->email->from('the email I used in the email.php', "Name");
        $this->email->to('email to send to');
        $this->email->subject('Test email');
        $this->email->message("Testing the email class");

        var_dump($this->email->send());
        $this->email->print_debugger();
     }

结果:

$array= array(4,3,4,3,1,2,1);
foreach($array as $v)
{
  $arr[$v][] = 1;
}
foreach($arr as $k => $v)
{
  if(count($v) == 1)
    $o[] = $k;
}

print_r($o);

答案 3 :(得分:0)

如果在您的情况下只能使用一个唯一值:

$array= array(4,3,4,3,1,2,1);
$singleValue = array_search(1, array_count_values($array));
var_dump($singleValue) // Outputs: 2