john
john

Reputation: 57

detect duplicate but ignore a value on PHP array

I know how to detect duplicate value in PHP array by using array_diff_key( $x , array_unique( $x ) );.

My problem is I want to detect duplicate value in PHP array, but ignore a value or NULL value. For example:

$x = array (1,0,0,0,4,4,3);
$x = array (1,NULL,NULL,NULL,4,4,3);

I want to detect 4 without changing the array structure (array length must still 7). Is this possible in PHP ? How to do that?

Upvotes: 1

Views: 121

Answers (2)

SaidbakR
SaidbakR

Reputation: 13534

I could do the following custom function detectArr:

<?php
$x = array (1,0,0,0,4,4,3);

    function detectArr($arr){
       $output = array();
       foreach ($arr as $i){
            if ($i){
                    $output[] = $i;
            }
            else{
                    $output[] = NULL;
            }        
       }
        return $output;
    }

    echo "<pre>";
    print_r(detectArr($x));

Checkout this DEMO: http://codepad.org/W8ocL6dj

Upvotes: 0

Dwayne Towell
Dwayne Towell

Reputation: 8583

Try this:

$y = array_filter($x,function($d){return $x!==null;});
$z = array_diff_key($y,array_unique($y));

$y has only the items NOT null.

$z has the keys of the duplicate items from $x that are not null.

Upvotes: 1

Related Questions