2

I'm trying to get all array elements, where the value only occurs once in the array.

I tried to use:

array_unique($array);

But this does only remove the duplicates, which is not what I want.

As an example:

$array =  0 => 1
          1 => 2
          2 => 3
          3 => 4
          4 => 5
          5 => 2
          6 => 3
          7 => 4
          8 => 5

Expected output:

array(
   0=>1
 )

As you can see only the value 1 occurs once in the array, all other values are more than once in the array. So I only want to keep that one element.

1

3 Answers 3

9

This should work for you:

First use array_count_values() to count how many times each value is in your array. This will return something like this:

Array (
    [1] => 1
    [2] => 2
    [3] => 2
    [4] => 2
    [5] => 2
//   ↑     ↑
// Value Amount
)

After that you can use array_filter() to only get the values, which occurs once in your array. Means:

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

And at the end simply use array_keys() to get the value from the original array.

Code:

<?php

    $arr = [1,2,3,4,5,2,3,4,5];
    $result = array_keys(array_filter(array_count_values($arr), function($v){
        return $v == 1;
    }));

    print_r($result);

?>

output:

Array (
    [0] => 1
)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use array_count_values to get the number of times each value exists in the array. You can use this to get all the values that occur only once by looking at the value in the returned array.

Comments

0

If you already have an array and it is in the structure described above, you should be able to just array_search(1, $array) and it will give you the key of the array with the value of 1. Or if you expect to have multiple keys with the value of 1, you can use array_keys($array, 1) and it will return an array of keys that have the value of 1. Hope this helps.

2 Comments

He's looking for array values that only appear once. That just happened to be the value 1. He's not literally looking for the value 1.
Okay I see, I missed that.

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.