Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Filtering and transformations

Use a predicate to select rows and a transformation to compute new values. array_filter preserves surviving keys, and array_map with one input also preserves keys.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

array_map($transform, array_filter($rows, $predicate));

Use a predicate to select rows and a transformation to compute new values. array_filter preserves surviving keys, and array_map with one input also preserves keys. Omitting the predicate removes false-like values, including a meaningful zero. Use array_values when a contiguous list is required.

$rows=[0,2,-1,3];$kept=array_filter($rows,fn($v)=>$v>=0);$scaled=array_map(fn($v)=>$v*10,$kept);
echo json_encode([array_keys($scaled),array_values($scaled),array_values(array_filter($rows))]);
[[0,1,3],[0,20,30],[2,-1,3]]

Examples

<?php
$rows=[0,2,-1,3];$kept=array_filter($rows,fn($v)=>$v>=0);$scaled=array_map(fn($v)=>$v*10,$kept);
echo json_encode([array_keys($scaled),array_values($scaled),array_values(array_filter($rows))]);

Result

[[0,1,3],[0,20,30],[2,-1,3]]

Sources