0

I have a PHP array that looks like this...

Array
(
    [item1] => Array
        (
            [0] => 1
            [1] => 1
            [2] => 1
        )

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

)

I am trying to count the values and output a new array that looks like this...

Array
(
    [item1] => Array
        (
            [1] => 3
        )

    [item2] => Array
        (
            [1] => 5
            [2] => 1
        )
)

I have tried to get the count by doing this...

print_r(array_count_values($myarray));

But this is not working for me, is there a way to count the values and creaye the new array all in one statement?

1
  • 4
    array_count_values works on one array. You have an array of arrays. You need some sort of loop here. Hint: array_map Commented Jan 31, 2020 at 15:42

3 Answers 3

2

You're on the right track, but you need to apply array_count_values() to each subarray, not the parent array.

$arr = [
    'item1' => [1, 1, 3],
    'item2' => [1, 1, 1, 2, 1],
    'item3' => [1, 2, 2, 2, 3, 3, 3, 3, 3, 3]
];

$totals = array_map('array_count_values', $arr);

print_r($totals);

Results in

Array
(
    [item1] => Array
        (
            [1] => 2
            [3] => 1
        )

    [item2] => Array
        (
            [1] => 4
            [2] => 1
        )

    [item3] => Array
        (
            [1] => 1
            [2] => 3
            [3] => 6
        )

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

Comments

1

So, as @deceze advised - it is:

// applying `array_count_values` to each element of `$array`
print_r(array_map('array_count_values', $array));

2 Comments

Thanks, works perfectly. How would I go about making this a new array instead of just outputting it with print_r?
@fightstarr20 Just assign the result to a new variable $newArray = array_map('array_count_values', $initialArray);
1

You have array into an another array, it means you can't use array_count_values() with this way, either use array_map() or use foreach and save data into one another array like:

<?php
$array = array(
      'item1'=>array(1,1,1),
      'item2'=>array(1,1,1,1,1,2)
  );

$newArray = array(); // your new array
foreach ($array as $key => $value) {
  $newArray[$key] = array_count_values($value);
}
echo "<pre>";
print_r($newArray);
?>

Result:

Array
(
    [item1] => Array
        (
            [1] => 3
        )

    [item2] => Array
        (
            [1] => 5
            [2] => 1
        )

)

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.