简体   繁体   中英

same values from php array in new array

i have a problem with arrays, there are not my friends :)

i have a this array:

Array
(
    [0] => 2012163115
    [1] => 2012163115
    [2] => 2012161817
    [3] => 201214321971
    [4] => 201214321971
    [5] => 201214321971
)

and i need this with all the variables appear more than once

Array
(
    [0] => 2012163115
    [1] => 201214321971
)

i try this

foreach ($array as $val) {
                    if (!in_array($val, $array_temp)) {
                        $array_temp[] = $val;
                    } else {
                        array_push($duplis, $val);
                    }
                }

but the result is

Array
(
    [0] => 2012163115
    [1] => 201214321971
    [2] => 201214321971
)

where is my mistake? thanks for help!

array_unique() is there for you.

EDIT: ops I didn't notice the "more than once" clause, in that case:

$yourArray = array('a', 'a', 'b', 'c');

$occurrences = array();

array_walk($yourArray, function($item) use(&$occurrences){

    $occurrences[$item]++;

});


$filtered = array();

foreach($occurrences as $key => $value){

    $value > 1 && $filtered[] = $key;

}

var_dump($filtered);
$array = array(
  '2012163115',
  '2012163115',
  '2012161817',
  '201214321971',
  '201214321971',
  '201214321971',
);

$duplication = array_count_values($array);
$duplicates = array();
array_walk($duplication, function($key, $value) use (&$duplicates){
  if ($key > 1)
    $duplicates[] = $value;
});
var_dump($duplicates);

Please see http://php.net/manual/en/function.array-unique.php#81513

These are added characters to make SO accept the post!

$array_counting = array();
foreach ($array as $val)
    if ( ! in_array($val, $array_counting))
    {
        $array_counting[$val] ++; // counting  
    }

$array_dups = array();
foreach ($array_counting as $key => $count)
{
    if ($count > 1)
        $array_dups[] = $key; // this is more than once
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM