Home > Enterprise >  How to declare a 100x100 matrix in PHP
How to declare a 100x100 matrix in PHP

Time:11-13

How can I declare a matrix having 100 rows and 100 columns in PHP?

Here is what I already know:

I know how to do it for 3x3:

$matrix=array(
    array(1,2,3),
    array(4,5,6),
    array(7,8,9)  
);

Or:

$matrix=[
    [1,2,3],
    [4,5,6],
    [7,8,9]
];

And then I have found a way of adding elements to a one dimensional array:

$t7=array("white","blue");
array_push($t7,"green","orange");

Thank you.

CodePudding user response:

You can do it with a couple of for loops, this is done only to a 5 x 5 matrix but just change the height and width to make it any size you like

$width = 5;
$height = 5;
$x = 1;

$matrix = [];

for( $i=0; $i < $width; $i  ) {
    for( $j=0; $j < $height; $j  ) {
        $matrix[$i][] = $x  ;
    }
}

print_r($matrix);

RESULT

Array
(
    [0] => Array ( [0] => 1,  [1] => 2,  [2] => 3,  [3] => 4,  [4] => 5 )
    [1] => Array ( [0] => 6,  [1] => 7,  [2] => 8,  [3] => 9,  [4] => 10 )
    [2] => Array ( [0] => 11, [1] => 12, [2] => 13, [3] => 14, [4] => 15 )
    [3] => Array ( [0] => 16, [1] => 17, [2] => 18, [3] => 19, [4] => 20 )
    [4] => Array ( [0] => 21, [1] => 22, [2] => 23, [3] => 24, [4] => 25 )
)

CodePudding user response:

<?php
$matrix = [];
$limit = 3;
$counter = 1;
for ($i = 0; $i < $limit; $i  ){
  $arr = [];
  for($j = 0; $j < $limit; $j  ) {
    $arr[] = $counter  ;
  }
  $matrix[$i] = $arr;  
}

print_r($matrix);

output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [1] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )

    [2] => Array
        (
            [0] => 7
            [1] => 8
            [2] => 9
        )

)

CodePudding user response:

Based on the comment from user 0stone0 here is the solution:

<?php

$n=100;

$matrix = array_fill(0,$n,array_fill(0,$n,0));

$matrix[7][7]=1234;

echo $matrix[7][7].' vs '.$matrix[7][8];

?>

Thank you 0stone0.

  •  Tags:  
  • php
  • Related