Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Display a two-dimensional array with two different nested loops in matrix form PHP?
In PHP, you can display a two-dimensional array in matrix form using nested loops − one loop for rows and another for columns. Use the tab character \t to create proper spacing between elements.
Syntax
for ($row = 0; $row < rows; $row++) {
for ($col = 0; $col < columns; $col++) {
echo $twoDimensionalArray[$row][$col], "\t";
}
echo "<br>"; // New line after each row
}
Example
Here's how to create and display a 3x3 matrix with nested loops ?
<?php
$twoDimensionalArray = [];
$value = 7;
// Fill the array
for ($row = 0; $row <= 2; $row++) {
for ($col = 0; $col <= 2; $col++) {
$twoDimensionalArray[$row][$col] = $value;
}
}
// Display the array in matrix form
for ($row = 0; $row <= 2; $row++) {
for ($col = 0; $col <= 2; $col++) {
echo $twoDimensionalArray[$row][$col] . "\t";
}
echo "<br>";
}
?>
7 7 7 7 7 7 7 7 7
Different Values Example
You can also create a matrix with different values for better visualization ?
<?php
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Display using nested loops
for ($i = 0; $i < count($matrix); $i++) {
for ($j = 0; $j < count($matrix[$i]); $j++) {
echo $matrix[$i][$j] . "\t";
}
echo "<br>";
}
?>
1 2 3 4 5 6 7 8 9
Conclusion
Using nested loops is the standard approach for displaying two-dimensional arrays in matrix form. The outer loop handles rows while the inner loop processes columns, with tab spacing for proper alignment.
Advertisements
