PHP array_keys and count
Count how many elements equal the price printed on an offer sign.
A simple example
array_keys and count
- Start with 2, 3, 2
- Do this Count matches for 2
- Result 2 matches
Syntax
count(array_keys($prices, 3, true))
Run these examples in PHP
Save one example at a time as lesson.php. Use PHP 8.2 or later.
php lesson.phpCount items at the offer price
A retailer checks a list of prices for a particular offer. Decide whether the question requires the presence of the price, its position or the number of occurrences before interpreting the result.
<?php
$prices = [8, 3, 12, 3];
echo (count(array_keys($prices, 3, true))), PHP_EOL;
2
The price of three appears twice, so two items qualify for the offer.
Count packs on the delivery slip
A loading desk receives four item counts in sequence. The supervisor asks how often the first quantity occurs in the complete batch. Count all matching entries.
Review print quantities
A print room records four job quantities, including a cancelled job. The supervisor asks how often the first quantity occurs in the complete batch. Count all matching entries.
What to watch for
Count the matching elements rather than the distinct matching prices.