PHP array_filter and array_values
array_filter keeps entries for which a callback returns true and preserves their keys. array_values reindexes the remaining values consecutively.
A simple example
array_filter and array_values
- Start with 0, −1, 2
- Do this Keep values at least zero
- Result 0, 2
Syntax
$kept = array_values(array_filter($readings, $predicate))
Run this example in PHP
Save the program as lesson.php. Use PHP 8.2 or later.
php lesson.php
Retain zero readings and reset numeric keys
A dataset includes a missing or optional measurement alongside actual numerical values. Make the missing-value policy explicit so a valid zero is not discarded or silently replaced.
<?php
declare(strict_types=1);
$readings = [null, 0, 7];
$available = array_filter($readings, static fn ($value): bool => $value !== null);
echo json_encode(array_values($available), JSON_THROW_ON_ERROR) . "\n";
[0,7]
An omitted predicate drops several false-like values, including zero. An explicit null check preserves real zero readings. Reset the keys before encoding when the result should be a JSON list.
PHP documentation for array_filter and array_values
Count packs on the delivery slip
A loading desk receives four item counts in sequence. Only positive quantities go to the packing desk. Which entries survive, in their original order?
Review print quantities
A print room records four job quantities, including a cancelled job. Only positive quantities go to the packing desk. Which entries survive, in their original order?