4

Okay, so I've got an array that has a ton of random numbers in it, like this...

$array = array(134, 12, 54, 134, 22, 22, 1, 9, 45, 45, 12, 134, 45, 134);

What I need to do, is find out what numbers are contained in my array, and if a number is duplicated in the array, I'd like to know how many times that number is found within the array. So taking the array that I listed above, I need the results to be something like this:

134: 4
12: 2
54: 1
22: 2
1: 1
9: 1
45: 3
etc.

Any bright ideas on how this might be accomplished?

Thanks!

3 Answers 3

8

See array_count_values.

<?php
print_r(array_count_values(
        array(134, 12, 54, 134, 22, 22, 1, 9, 45, 45, 12, 134, 45, 134)));

gives:

Array
(
    [134] => 4
    [12] => 2
    [54] => 1
    [22] => 2
    [1] => 1
    [9] => 1
    [45] => 3
)
Sign up to request clarification or add additional context in comments.

1 Comment

And here I am writing a function to answer the authors question. Didn't know this function existed. Thanks!
2

Use array_count_values() to count the occurrences of each unique value:

$counts = array_count_values($array);
var_dump($counts);

Output:

array(7) {
  [134]=>
  int(4)
  [12]=>
  int(2)
  [54]=>
  int(1)
  [22]=>
  int(2)
  [1]=>
  int(1)
  [9]=>
  int(1)
  [45]=>
  int(3)
}

Comments

2

You can use the function:

array_count_values($array)

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.