How to search for a number in a sorted matrix in PHP

1 Answer

0 votes
function searchMatrix(array $matrix, int $target): bool {
    $rows = count($matrix);
    $cols = count($matrix[0]);

    $row = 0;
    $col = $cols - 1;

    while ($row < $rows && $col >= 0) {
        $value = $matrix[$row][$col];
        if ($value === $target) {
            echo "Found: i = $row j = $col\n";
            return true;
        } elseif ($value > $target) {
            $col--;
        } else {
            $row++;
        }
    }

    echo "Not found\n";
    return false;
}

$matrix = [
    [2, 3, 5, 7, 8],
    [10, 13, 17, 18, 19],
    [25, 26, 30, 37, 38],
    [43, 46, 50, 51, 99]
];

searchMatrix($matrix, 37);



/*
run:

Found: i = 2 j = 3

*/

 



answered Oct 7, 2025 by avibootz
...