Kieran
Kieran

Reputation: 69

Changing the size of a two-dimensional array based on user input

Is it possible to generate a 2-dimensional array based on user input?

For example, I currently have an array of size 2x2, which I have written as follows:

<?php
    $matrix = array(
        array($a, $b),
        array($c, $d)
    );
?>

As you can see, this array is full of variables. My question is, if I was to have a text input where a user could set the parameters of the desired array, i.e.

<p>The size of my Matrix will be:</p>
<p>Columns:<input type='text' name='columns'> Rows:<input type='text' name='rows'></p>
<input type='submit' value='Compile my Matrices!' name='submit'>  

So if the user has input 3 columns and 3 rows (3x3), how would I go about creating an array that follows the same format as the 2x2 example so that the dynamic outputted array would be:

<?php
    $matrix = array(
        array($a, $b, $c),
        array($d, $e, $f),
        array($g, $h, $i)
    );
?>

Is it also possible to fill the array with these variables upon generation?

EDIT - The variables will be declared elsewhere, ie.

<?php
    $a = rand($min, $max);
    $b = rand($min, $max);
    $c = rand($min, $max);
    $d = rand($min, $max); etc etc
?>

where $min and $max are set by other parameters.

EDIT2 - After a little messing around, I have managed to create a matrix which could follow the correct format I require:

for ($i = 0; $i < 5; $i++) {
    for ($j=0; $j < 5; $j++){
         $matrix[$i][$j] = ('a' . $counter);
         $counter++;
         //echo $matrix[$i][$j] . ' ';
    }
    //echo '<br>';
}

This produces an array of format:

a0 a1 a2 a3 a4
a5 a6 a7 a8 a9
a10 a11 a12 a13 a14
a15 a16 a17 a18 a19
a20 a21 a22 a23 a24 

which is close to what I need.

Upvotes: 1

Views: 341

Answers (1)

jeffery_the_wind
jeffery_the_wind

Reputation: 18198

Assuming you know how to POST the data from the html form back to your server, the php code which processes the request could look something like the following. It seems your question comes down to how to code a dynamically sized 2-dimensional array (matrix).

create a nested for loop. The inner for loop builds each row ( $this_row ) by appending items to it: $this_row[] = rand($min, $max);, then each new row is appended to the $matrix array.

Keep in mind the rand function and $min and $max variables are not defined in the following example. You'll need to define them.

<?php

    $num_cols = filter_input(INPUT_POST, 'columns', FILTER_VALIDATE_INT);
    $num_rows = filter_input(INPUT_POST, 'rows', FILTER_VALIDATE_INT);

    $matrix = array();

    for ( $j = 0; $j < $num_rows; $j ++ ) {
        $this_row = array()
        for ( $k = 0; $k < $num_cols; $k ++ ) {
            $this_row[] = rand($min, $max);
        }
        $matrix[] = $this_row;
    }

    //now you have your matrix

?>

Upvotes: 1

Related Questions