PHP Code Examples

Transform and Filter Arrays with PHP

Combine array_map() and array_filter() to normalize and select values from a dataset.

Example

<?php
$prices = [12.5, 0, 24.99, -3, 8];

$validPrices = array_filter(
    $prices,
    static fn (float $price): bool => $price > 0
);

$formatted = array_map(
    static fn (float $price): string => number_format($price, 2),
    $validPrices
);

print_r($formatted);

Explanation

array_filter() keeps elements that satisfy a condition. array_map() transforms each remaining value.

By default, array_filter() preserves original array keys. Use array_values($validPrices) if you need consecutive numeric indexes.

Share this page Help other developers discover this resource.