Reputation: 69
So I have the following PHP script to add to random matrices together in order to create a dynamic type of question for a Quiz:
<?php
$min = 0;
$max = 10;
$a1 = rand($min, $max);
$b1 = rand($min, $max);
$c1 = rand($min, $max);
$d1 = rand($min, $max);
$a2 = rand($min, $max);
$b2 = rand($min, $max);
$c2 = rand($min, $max);
$d2 = rand($min, $max);
$matrixa = array(
array($a1,$b1),
array($c1, $d1)
);
$matrixb = array(
array($a2,$b2),
array($c2, $d2)
);
for ($i=0; $i<2; $i++){
for ($j=0; $j<2; $j++){
$matresult[$i][$j] = $matrixa[$i][$j] + $matrixb[$i][$j];
echo $matresult[$i][$j] . ' ';
}
echo '<br>';
}
var_dump($matresult);
?>
This works, and stores the values correctly so that the output is as follows:
16 4
4 8
array(2) { [0]=> array(2) { [0]=> int(16) [1]=> int(4) } [1]=> array(2) { [0]=> int(4) [1]=> int(8) } }
(For example)
Now, when I try to use a session variable within the same for loop:
for ($i=0; $i<2; $i++){
for ($j=0; $j<2; $j++){
$_SESSION['matresult[$i][$j'] = $matrixa[$i][$j] + $matrixb[$i][$j];
echo $_SESSION['matresult[$i][$j]'] . ' ';
}
echo '<br>';
}
var_dump($_SESSION['matresult']);
The output gives the following:
16 4
4 8
NULL
I don't understand why this is happening, the code and logic is exactly the same, what have I missed?
Upvotes: 0
Views: 1452
Reputation: 2216
You could just put your array into the session outside the loop:
for ($i=0; $i<2; $i++){
for ($j=0; $j<2; $j++){
$matresult[$i][$j] = $matrixa[$i][$j] + $matrixb[$i][$j];
echo $matresult[$i][$j] . ' ';
}
echo '<br>';
}
$_SESSION['matresult'] = $matresult;
Upvotes: 0
Reputation: 5690
try this code
for ($i=0; $i<2; $i++){
for ($j=0; $j<2; $j++){
$_SESSION['matresult'][$i][$j] = $matrixa[$i][$j] + $matrixb[$i][$j];
echo $_SESSION['matresult'][$i][$j] . ' ';
}
echo '<br>';
}
var_dump($_SESSION['matresult']);
this is main index so when you want to add more then define like this
$_SESSION['matresult'][][]....
Upvotes: 0
Reputation: 59
Make sure that your session has a valid key
for ($i=0; $i<2; $i++){
for ($j=0; $j<2; $j++){
$_SESSION['matresult'][$i][$j] = $matrixa[$i][$j] + $matrixb[$i][$j];
echo $_SESSION['matresult'][$i][$j] . ' ';
}
echo '<br>';
}
var_dump($_SESSION['matresult']);
this is main index so when you want to add more then define like this
$_SESSION['matresult'][][]....
Upvotes: 1
Reputation: 436
I changed
$_SESSION['matresult[$i][$j'] = $matrixa[$i][$j] + $matrixb[$i][$j];
echo $_SESSION['matresult[$i][$j]'] . ' ';
to
$_SESSION['matresult'][$i][$j] = $matrixa[$i][$j] + $matrixb[$i][$j];
echo $_SESSION['matresult'][$i][$j] . ' ';
This code should work as espected:
<?php
....
for ($i=0; $i<2; $i++){
for ($j=0; $j<2; $j++){
$_SESSION['matresult'][$i][$j] = $matrixa[$i][$j] + $matrixb[$i][$j];
echo $_SESSION['matresult'][$i][$j] . ' ';
}
echo '<br>';
}
var_dump($_SESSION['matresult']);
?>
Upvotes: 3