Learn/PHP/13. Counting, grouping and sets
Lesson 13 of 15
Sign in

PHP, lesson 13

Counting, grouping and sets

Associative arrays find a value by its key in roughly constant time, however big the array gets. That makes them the right tool for three everyday jobs: counting things, grouping things and comparing groups.

Counting

The hand-written pattern reads the current count with a fallback of 0 and adds one:

For a plain list of strings or integers, array_count_values() does the whole job in one call:

Remember from lesson 7 that numeric-looking string keys become integers: counting the words "10" and "7" produces keys 10 and 7. That rarely matters, but it can surprise you when you sort keys or compare them with ===.

Grouping

Appending to $groups[$key][] creates the inner array automatically the first time a key appears, so grouping takes one line:

2 exercises to try what you just read.

Exercise 1

Most used words

Press Ctrl Enter or Check to test your code.

Exercise 2

Club overlap

Press Ctrl Enter or Check to test your code.

array_column() is another grouping helper: given a list of rows, it pulls out one column, optionally keyed by another column: array_column($rows, "price", "name").

Sets

PHP has no separate set type. You have two ways to model one.

A list of unique values. array_unique() removes duplicates, and the set operations work on values:

FunctionResult
array_intersect($a, $b)values in both
array_diff($a, $b)values in $a but not in $b
array_unique(array_merge($a, $b))values in either (union)

These functions keep the original keys, so the result may have gaps such as [0 => "a", 2 => "c"]. Wrap the result in array_values() when you need a clean list, and call sort() when you want a predictable order.

Keys of an array. For fast membership tests, store the items as keys. array_flip() swaps keys and values, and isset() then checks membership instantly, even with millions of items:

in_array() has to scan the whole list each time, so for repeated lookups the isset() approach is far faster.

Helpful extras

  • array_keys($a) and array_values($a) split an array into its keys and values.
  • array_key_exists($k, $a) checks for a key even when its value is null.
  • array_fill_keys(["a", "b"], 0) builds ["a" => 0, "b" => 0], handy for starting counts.
  • count($a) tells you how many distinct keys a map has.

Further reading

  • array_count_values()
  • array_intersect()
  • array_diff()
  • array_flip()
  • Arrays

Read all of the input. Make it lowercase, split it on whitespace and trim the punctuation characters .,!?;: from both ends of each word (skip words that become empty). Print the three most frequent words as word count, most frequent first, breaking ties alphabetically. With fewer than three distinct words, print them all. Words contain letters only.

Sample input:

Sample output:

The chess club and the drama club each send a member list. The first input line holds the chess members and the second line the drama members, separated by spaces. Either line may be empty, and a name may be repeated by mistake.

Print three lines, each listing names alphabetically separated by single spaces (just the label if the group is empty):

Sample input:

Sample output:

<?php

$counts = [];
foreach (["apple", "pear", "apple"] as $fruit) {
    $counts[$fruit] = ($counts[$fruit] ?? 0) + 1;
}
// ["apple" => 2, "pear" => 1]
<?php

$votes = array_count_values(["red", "blue", "red", "green", "red"]);
// ["red" => 3, "blue" => 1, "green" => 1]
arsort($votes);            // most votes first, names stay attached
echo array_key_first($votes), "\n";   // red
<?php

$groups = [];
foreach (["ant", "bee", "asp", "cat"] as $word) {
    $groups[$word[0]][] = $word;
}
// ["a" => ["ant", "asp"], "b" => ["bee"], "c" => ["cat"]]
<?php

$banned = array_flip(["spam", "scam"]);   // ["spam" => 0, "scam" => 1]
var_dump(isset($banned["spam"]));        // bool(true)
The cat sat. The dog sat!
The end?
the 3
sat 2
cat 1
both: <in both clubs>
chess only: <only in chess>
drama only: <only in drama>
ana ben cleo ben
cleo dev ana
both: ana cleo
chess only: ben
drama only: dev