How to find the two largest elements in an array with PHP

1 Answer

0 votes
declare(strict_types=1);

/**
 * Finds the two largest elements in an array.
 *
 * @param array<int> $numbers Input array of integers.
 *
 * @return array{
 *     largest:int,
 *     secondLargest:int
 * }
 *
 * @throws InvalidArgumentException If the array contains fewer than 2 elements.
 */
function findTwoLargest(array $numbers): array
{
    if (count($numbers) < 2) {
        throw new InvalidArgumentException(
            'Array must contain at least two elements.'
        );
    }

    $largest = PHP_INT_MIN;
    $secondLargest = PHP_INT_MIN;

    foreach ($numbers as $value) {
        if ($value > $largest) {
            $secondLargest = $largest;
            $largest = $value;
        } elseif ($value > $secondLargest) {
            $secondLargest = $value;
        }
    }

    return [
        'largest' => $largest,
        'secondLargest' => $secondLargest,
    ];
}

// Input data
$numbers = [3, 4, 9, 6, 7, 1, 2, 5];

// Find the two largest elements
$result = findTwoLargest($numbers);

// Display results
echo 'Array: ' . implode(', ', $numbers) . PHP_EOL;
echo 'Largest element: ' . $result['largest'] . PHP_EOL;
echo 'Second largest element: ' . $result['secondLargest'] . PHP_EOL;


/*
run:

Array: 3, 4, 9, 6, 7, 1, 2, 5
Largest element: 9
Second largest element: 7

*/

 



answered 16 hours ago by avibootz
...