Library contents

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

  1. Start with 0, −1, 2
  2. Do this Keep values at least zero
  3. Result 0, 2
Zero passes the predicate. Resetting the numeric keys makes these two values consecutive entries.

Syntax

PHP 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.

From the programdeclare(strict_types=1)
Result[0,7]
lesson.php
<?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";
Output
[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

Advertisements

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?

Given6 · 2 · 6 · 0
Worked result6 · 2 · 6

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?

Given3 · 0 · 8 · 3
Worked result3 · 8 · 3