2

Given array like this:

$products = array([0] => Apple, [1] => Orange, [2] => Orange, [3] => Strawberry, [4] => Orange, [5] => Mango, [6] => Orange, [7] => Strawberry, [8] => Orange, [9] => Orange, [10] => Orange);

I need to count number of similar values and receive array where each unique value will appear once along with the count of its occurrences from original array. For example the new array should look like this:

$new_products = array([0] => "Apple 1", [1] => "Orange 7", [2] => "Strawberry 2", [3] => "Mango 1");

Using functions below I can receive 2 arrays:

array_keys(array_count_values($products))); // Return array of unique values
array_values(array_count_values($products))); // Return array with count for each unique values

Will return:

Array ( [0] => Apple 1 [1] => Orange [2] => Strawberry  [3] => Mango )
Array ( [0] => 1 [1] => 7 [2] => 2 [3] => 1 ) 

I cant find a way to merge the values so I get the array that looks like $new_products array in my example.

6
  • 2
    $result = array_map(function ($i1, $i2) { return $i1. ' ' . $i2; }, $ar_keys, $ar_counts); Commented Apr 5, 2016 at 12:32
  • 1
    hi, @Uchiha ! hundred years have not seen :) Commented Apr 5, 2016 at 12:42
  • @Uchiha, sometimes it's so nice to read in my native language :) Commented Apr 5, 2016 at 12:47
  • @splash58 Yep thats great somewhat active on SO Commented Apr 5, 2016 at 12:47
  • 2
    @Sergio look there - eval.in/547943 Commented Apr 5, 2016 at 12:53

2 Answers 2

5

Just iterate array_count_values with foreach.

$new_products = [];
foreach (array_count_values($products) as $name => $count) {
  $new_products[] = $name. ' '. $count;
}
Sign up to request clarification or add additional context in comments.

Comments

2

Try this function:

<?php

$products = array(
    0 => 'Apple', 
    1 => 'Orange', 
    2 => 'Orange', 
    3 => 'Strawberry', 
    4 => 'Orange', 
    5 => 'Mango', 
    6 => 'Orange', 
    7 => 'Strawberry', 
    8 => 'Orange', 
    9 => 'Orange', 
    10 => 'Orange'
);

function getNamesWithCountArray($array)
{
    $result = array();
    $countedValues = array_count_values($array);

    foreach($countedValues as $key => $value)
        $result[] = $key . ' ' . $value;

    return $result;
}

$new_products = getNamesWithCountArray($products);

echo '<pre>';
print_r($new_products);

Result of print_r($new_products); is:

Array
(
    [0] => Apple 1
    [1] => Orange 7
    [2] => Strawberry 2
    [3] => Mango 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.