To create a Two Dimensional Array in PHP, you can use nested array initialization.
In this example,
$matrix
with dimensions 3x3.<?php
$matrix = [];
for ($i = 0; $i < 3; $i++) {
$matrix[$i] = [];
for ($j = 0; $j < 3; $j++) {
$matrix[$i][$j] = $i + $j;
}
}
print_r($matrix);
?>
Array ( [0] => Array ( [0] => 0 [1] => 1 [2] => 2 ) [1] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [2] => Array ( [0] => 2 [1] => 3 [2] => 4 ) )
In this example,
$matrix
with dimensions 2x2.<?php
$matrix = [];
for ($i = 0; $i < 2; $i++) {
$matrix[$i] = [];
for ($j = 0; $j < 2; $j++) {
$matrix[$i][$j] = 'Row ' . ($i + 1) . ', Column ' . ($j + 1);
}
}
print_r($matrix);
?>
Array ( [0] => Array ( [0] => Row 1, Column 1 [1] => Row 1, Column 2 ) [1] => Array ( [0] => Row 2, Column 1 [1] => Row 2, Column 2 ) )
In this tutorial, we learned How to create a Two Dimensional Array in PHP language with well detailed examples.