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);