map, filter, walk

Converting Elements with map, filter and walk

array_map($fn, $a) returns a new array of results, keeping keys when given one array; given several it walks them in step, and a null callback zips them. array_filter($a, $fn) keeps elements whose callback returns true and preserves keys; with no callback it drops falsy values, and ARRAY_FILTER_USE_KEY passes keys in. array_walk() edits in place through a reference parameter.

Adding tax, zipping, filtering and discounting in placePHP
<?php
$prices = ['BK-101' => 9.99, 'BK-205' => 4.5, 'BK-300' => 12.0, 'BK-410' => 0.0];
echo json_encode(array_map(fn(float $p): float => round($p * 1.08, 2), $prices)), "\n";
$cheap = array_filter($prices, fn(float $p): bool => $p > 0 && $p < 10);          // keys kept
echo json_encode($cheap), ' ', json_encode(array_values($cheap)), ' ',
  json_encode(array_filter([0, '0', '', null, [], 'Dune'])), "\n";              // truthy only
array_walk($prices, function (float &$p, string $sku, float $rate): void {
  $p = round($p * $rate, 2);                                                    // in place
}, 0.9);
echo json_encode($prices), ' ', json_encode(array_flip(['sf' => 'SF'])), ' ',
  json_encode(array_unique(['SF', 'Poetry', 'SF'])), "\n";
Output
{"BK-101":10.79,"BK-205":4.86,"BK-300":12.96,"BK-410":0}
{"BK-101":9.99,"BK-205":4.5} [9.99,4.5] {"5":"Dune"}
{"BK-101":8.99,"BK-205":4.05,"BK-300":10.8,"BK-410":0} {"SF":"sf"} ["SF","Poetry"]

Because array_filter() keeps keys, [9.99, 4.5] needed array_values() to become a JSON array. array_flip() swaps keys and values, array_unique() drops repeats, keeping the first key, and array_walk_recursive() visits the leaves of nested arrays.