PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 22, 2022

[FIXED] How to declare 2d matrix array PHP

 January 22, 2022     arrays, matrix, multidimensional-array, php     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing