Linz Darlington
Linz Darlington

Reputation: 671

Create an array with counts of values from another array with the value as a key and the count as the value

I've just surveyed my seven friends about their favourite fruit (not!) and I want to provide the results in an array e.g.

Array ( [Apple] => 4 [Orange] => 1 [Strawberry] => 2 [Pear] => 0 ).

I've come up with a solution for this, but it seems in elegant. Is there a way of doing this within the 'foreach', rather than having to use the array combine. Thank you.

// Set the array of favourite fruit options.

$fruitlist = array('Apple', 'Orange', 'Strawberry', 'Pear');

// Survey results from seven people
$favouritefruitlist = array('Apple', 'Apple', 'Orange', 'Apple','Strawberry', 'Apple', 'Strawberry');

// Create an array to count the number of favourites for each option
$fruitcount = [];
   foreach ($fruitlist as $favouritefruit) {
      $fruitcount[] = count(array_keys($favouritefruitlist, $favouritefruit));
    }

// Combine the keys and the values
$fruitcount = array_combine ($fruitlist, $fruitcount);

print_r($fruitcount);

Upvotes: 1

Views: 641

Answers (2)

hsz
hsz

Reputation: 152216

Just try with array_count_values

$fruitcount = array_count_values($favouritefruitlist);

To have also 0 values you, try:

$initial = array_fill_keys($fruitlist, 0);
$counts = array_count_values($favouritefruitlist);
$fruitcount = array_merge($initial, $counts);

Upvotes: 4

roberto06
roberto06

Reputation: 3864

In case you still want to use foreach instead of array_count_values, you should loop over $fruitlist first to build the keys, then over $favouritefruitlist to populate the array, as such :

<?php
// Set the array of favourite fruit options.
$fruitlist = array('Apple', 'Orange', 'Strawberry', 'Pear');

// Survey results from seven people
$favouritefruitlist = array('Apple', 'Apple', 'Orange', 'Apple', 'Strawberry', 'Apple', 'Strawberry');

// Create an array to count the number of favourites for each option
$fruitcount = [];
foreach ($fruitlist as $fruit) {
    $fruitcount[$fruit] = 0;
}
foreach ($favouritefruitlist as $favouritefruit) {
    $fruitcount[$favouritefruit]++;
}

print_r($fruitcount);

Result :

Array
(
    [Apple] => 4
    [Orange] => 1
    [Strawberry] => 2
    [Pear] => 0
)

(BTW, I can't believe none of your friends like pears...)

Upvotes: 1

Related Questions