How to display the upper triangular matrix in PHP

1 Answer

0 votes
function printUpperTriangular($matrix) {
    $rows = count($matrix);  
    $cols = count($matrix[0]);  
    
    for ($i = 0; $i < $rows; $i++) {
        for ($j = 0; $j < $cols; $j++) {
            if ($i > $j) {
                echo "0" . " ";
            }
            else {
                echo $matrix[$i][$j] . " ";
            }
        }
        echo "\n";
    }
}
 
$matrix = array(array(1, 2, 3),
                array(4, 5, 6),
                array(7, 8, 9));
 
printUpperTriangular($matrix);




/*
run:

1 2 3 
0 5 6 
0 0 9 

*/

 



answered Aug 28, 2021 by avibootz

Related questions

1 answer 128 views
1 answer 119 views
1 answer 145 views
1 answer 166 views
1 answer 200 views
1 answer 184 views
1 answer 144 views
...