1

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?

6
  • Is this possible in PHP ? yes, it is possible with php Commented Jan 1, 2015 at 5:08
  • 1
    1. read rules of this site 2. write code 3. post clear question Commented Jan 1, 2015 at 5:10
  • You can use array_intersect_assoc Commented Jan 1, 2015 at 5:19
  • Use array_filter to remove the values you want to ignore before checking for duplicates. None of these functions change the original array structure, they return new arrays. Commented Jan 1, 2015 at 5:50
  • Please explain it in detail Commented Jan 1, 2015 at 6:48

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.