Saturday, January 22, 2022

[FIXED] How to declare 2d matrix array PHP

Issue

Here's a piece of PHP code that should declare 2D Array.

$array = array(
    range(1, 4), 
    range(1, 4)
);

print_r($array);

It should look like this:Array

But the output is: Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) [1] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) )

So what am I doing wrong? How can I declare\display as a matrix 2d array?


Solution

You adding range only to first 2 indexs.

$array = array(
 range(1, 4), 
 range(1, 4),
 range(1, 4), 
 range(1, 4)
);

If you want better option:

$matrix=  array();

foreach (range(1,4) as $row) {
 foreach (range(1,4) as $col) {
  $matrix[$row][$col] = "some val";
 }
}


print_r($matrix);

For HTML output

<table border="1">
<?php foreach (range(1,4) as $row) { ?>
<tr>
<?php foreach (range(1,4) as $col) { ?>
<td><?php echo $row.$col; ?></td>
<?php  } ?>
</tr>
<?php } ?>
</table>


Answered By - VK321

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.