<?php
/*
Find the N smallest values in a 2D array.
Approach:
1. Flatten the 2D array into a single list.
2. Sort the list.
3. Take the first N values.
PHP's built‑in array functions make this approach both expressive
and efficient for typical workloads.
*/
/* Flatten a 2D array into a single list */
function flatten(array $matrix): array
{
$result = [];
// Iterate through each row and merge its values
foreach ($matrix as $row) {
$result = array_merge($result, $row);
}
return $result;
}
/* Extract the N smallest values */
function smallestN(array $matrix, int $n): array
{
$flat = flatten($matrix);
// Sort ascending
sort($flat);
// Return the first N values
return array_slice($flat, 0, $n);
}
/* Main */
$matrix = [
[42, 12, 85, 3],
[ 7, 99, 15, 23],
[64, 1, 18, 30],
[ 3, 55, 11, 90]
];
$n = 5;
$values = smallestN($matrix, $n);
echo "The $n smallest values:\n";
foreach ($values as $v) {
echo $v . " ";
}
/*
run:
The 5 smallest values:
1 3 3 7 11
*/