Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,709 questions

55,473 answers

573 users

How to find the N smallest values in a 2D array in PHP

1 Answer

0 votes
<?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 

*/

 



answered 4 days ago by avibootz
...