Library contents

PHP array_count_values

array_count_values counts occurrences of integer and string values and uses those values as keys in the result.

A simple example

array_count_values

  1. Start with A, B, A
  2. Do this Count each key
  3. Result A has 2, B has 1
The second A increases the existing A count from one to two.

Syntax

PHP syntax
$counts = array_count_values($statuses)
Run this example in PHP

Save the program as lesson.php. Use PHP 8.2 or later.

php lesson.php

Build a frequency table from order statuses

An operations report receives repeated statuses or events. Decide whether it needs totals, consecutive runs or a snapshot before grouping so the summary preserves the distinctions the operator needs.

From the programdeclare(strict_types=1)
First output linenew=2
lesson.php
<?php
declare(strict_types=1);

$counts = array_count_values(['new', 'sent', 'new']);
foreach (['new', 'held'] as $status) {
    printf("%s=%d\n", $status, $counts[$status] ?? 0);
}
Output
new=2
held=0

An unseen category has no entry. Use the null-coalescing operator to supply zero when printing every expected category.

PHP documentation for array_count_values

Advertisements

Count north-door returns

A gallery receives entrance codes from four ticket desks. Count how often the specified code occurs when grouping the records. Which count belongs on that code’s row?

GivenN · S · N · N | count N
Worked result3

Count ready print jobs

A print desk groups the current jobs by status. Count how often the specified code occurs when grouping the records. Which count belongs on that code’s row?

Givenready · held · ready | count ready
Worked result2