php - Count the total occurrences of each unique word in a flat array of multi-word elements ← (PHP)

Input array:

$array = [
    'Mary',
    'Mary had a little',
    'a lamb',
    'Mary mary mary',
    'lady'
];

Desired output:

[
    'Mary' => 5,
    'a' => 2,
    'had' = 1,
    'little' => 1,
    'lady' => 1
]

Answer



Solution:

<?php
$array=array(
0 => 'Mary',
1 => 'Mary had a little',
2 => 'a lamb',
3 => 'Mary mary mary',
4 => 'lady'
);
$data=array();
foreach($array as $sentence)
{
    //gatering words in an array by spliting the sentence on space.
    $data=  array_merge($data,explode(" ", $sentence));
}
//counting values present in array for case sensitive
$result=array_count_values($data);
print_r($result); //Result 1

//counting values present in array for case insensitive by changing each array element to lowercase
$result=array_count_values(array_map("strtolower", $data));
print_r($result); //Result 2

Output:

//result 1
Array
(
    [Mary] => 3
    [had] => 1
    [a] => 2
    [little] => 1
    [lamb] => 1
    [mary] => 2
    [lady] => 1
)
//result 2
Array
(
    [mary] => 5
    [had] => 1
    [a] => 2
    [little] => 1
    [lamb] => 1
    [lady] => 1
)

Answer



Solution:

It is inefficient to make iterated calls of explode() and array_merge(). Just let implode() condense the data into a string, reduce the case, convert back to a 1-dimensional array, then count. Easy.

Code: (Demo)

$array = [
    'Mary',
    'Mary had a little',
    'a lamb',
    'Mary mary mary',
    'lady'
];

var_export(
    array_count_values(
        explode(' ',
            strtolower(
               implode(' ', $array)
            )
        )
    )
);

Output:

array (
  'mary' => 5,
  'had' => 1,
  'a' => 2,
  'little' => 1,
  'lamb' => 1,
  'lady' => 1,
)

Source