0

I would like to count all the repeated values in a mysql result array. For example

array (
[0] = > array (
 ["id"] => 1
["n"] => "ab"
)
[1] = > array (
 ["id"] => 5
["n"] => "bc"
)
[2] = > array (
 ["id"] => 4
["n"] => "cd"
)
[3] = > array (
 ["id"] => 1
["n"] => "ef"
)
)

So, taking the multidemensional array above, I want to count the amount of times each value of id is repeated in the array.

The result would be

1 = 2 times
5 = 1 time
4 = 1 time

I know I can do this with the array_search() function, but in my case, I don't know what i'm searching for. I just need the amount of results that have a specific repeated value.

2
  • be easy with a foreach loop, but there are other ways Commented Jun 24, 2015 at 23:48
  • @Dagon Please elaborate Commented Jun 24, 2015 at 23:49

2 Answers 2

1

You can use array_count_values()

$array = array ( 0 => array("id" => 1, "n" => "ab"), 1 => array("id" => 5, "n" => "bc"), 2 => array("id" => 4, "n" => "cd"), 3 => array("id" => 1, "n" => "ef"));
$counts = array_count_values(array_column($array, "id"));
print_r($counts);
Sign up to request clarification or add additional context in comments.

Comments

0

You can try the following, using foreach loop:

$final = array();
foreach($array as $ar)
    $final[$ar["id"]] = isset($final[$ar["id"]]) ? $final[$ar["id"]] + 1 : 1; 

Output:

array(3) {
  [1]=>
  int(2)
  [5]=>
  int(1)
  [4]=>
  int(1)
}

Demonstration

8 Comments

In my case, the values that are repeated aren't only numbers. They're random strings similar to an md5 hash with both number and letters. Would this still work?
@user4559334: Yes, it will
nevermind. It works. There was a small error on my part
@user4559334: Well, you can use foreach to iterate through $final array too.
@user4559334: these are your keys, you can access array elements with it like $final["559551b78f154a04427b41d16d8614c8a855"]. It is not fancy, but as long as you are using hashed values it is the option.
|

Your Answer

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