phen0menon
phen0menon

Reputation: 2452

How to declare 2d matrix array PHP

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?

Upvotes: 0

Views: 9838

Answers (2)

COil
COil

Reputation: 7596

Found a (shorter) alternative in a PHP doc comment. Interesting as it is a one liner and 4 can be replaced by a variable:

$array = array_fill(1, 4, array_fill(1, 4, ''));

Upvotes: 1

VK321
VK321

Reputation: 5953

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>

Upvotes: 5

Related Questions