Skip to content
PHP Logo

What are the best practices for validating the uniqueness of numbers in a Sudoku puzzle grid using PHP?

When validating the uniqueness of numbers in a Sudoku puzzle grid using PHP, it is important to check that each row, column, and 3x3 subgrid contains only unique numbers from 1 to 9. This can be achieved by iterating through each row, column, and subgrid and keeping track of the numbers encountered.

php
function validateSudoku($grid) {
    for ($i = 0; $i < 9; $i++) {
        $row = [];
        $column = [];
        $subgrid = [];
        
        for ($j = 0; $j < 9; $j++) {
            // Check rows
            if (in_array($grid[$i][$j], $row) || in_array($grid[$j][$i], $column) || in_array($grid[3*intdiv($i,3)+intdiv($j,3)][3*($i%3)+($j%3)], $subgrid)) {
                return false;
            }
            
            $row[] = $grid[$i][$j];
            $column[] = $grid[$j][$i];
            $subgrid[] = $grid[3*intdiv($i,3)+intdiv($j,3)][3*($i%3)+($j%3)];
        }
    }
    
    return true;
}