Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,880 questions

51,806 answers

573 users

How to create an M x N matrix with random numbers in PHP

1 Answer

0 votes
function printMatrix($matrix) {
    $rows = count($matrix);
    $cols = count($matrix[0]);
    
    for ($i = 0; $i < $rows; $i++) {
        for ($j = 0; $j < $cols; $j++) {
            printf("%4d", $matrix[$i][$j]);
        }
        echo "\n";
    }
}
 
function generateRandomMatrix($rows, $cols)  {
    $matrix = array_fill(0, $rows, array_fill(0, $cols, 0));
     
    for ($i = 0; $i < $rows; $i++) {
        for ($j = 0; $j < $cols; $j++) {
            $matrix[$i][$j] = rand(1, 100);
        }
    }
    return $matrix;
}
         
$matrix = generateRandomMatrix(4, 5);
 
printMatrix($matrix);




/*
run:

  42  93  55  29   3
  13   9  30  49   6
  70  49  70  33   7
  43  17  11  47  73

*/

 



answered May 15, 2024 by avibootz
...