Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP Array Losing Values Outside of Function
    primarykey
    data
    text
    <p>Hey guys I have a weird problem trying to use a global array in php.</p> <p>I don't even really want to use a global but here's what i'm trying to do.</p> <p>I have 2 functions</p> <p>createMatrix($name) which creates a 5x5 matrix of texts boxes and remembers values loadMatrix($name) which loads a 5x5 matrix from post data.</p> <p>For some reason, after I run loadMatrix(), the values I set are lost in createMatrix()</p> <p>I've tried a ton of debugging methods and declaring my matrix variables as globals but no luck. I know it's a scope issue because when I tried running everything outside of the functions it worked just fine.</p> <pre><code>&lt;form action="Program4.php" method="post"&gt; &lt;?php $matrixa = array(array()); $matrixb = array(array()); if($_POST['add']) echo "Add Clicked"; if($_POST['subtract']) echo "Subtract Clicked"; function loadArrays($name1,$name2) { //The Solution: global $matrixa, $matrixb; for($x = 0; $x &lt; 5; $x++) for($y = 0; $y &lt; 5; $y++) { $matrixa[$x][$y] = $_POST[$name1 . $x . $y]; $matrixb[$x][$y] = $_POST[$name2 . $x . $y]; } } function createMatrix($name) { //The Solution: global $matrixa, $matrixb; echo "&lt;h2&gt;" . $name . "&lt;/h2&gt;\n"; for($x = 0; $x &lt; 5; $x++) echo $matrixa[0][$x]; echo "&lt;div style=\"border:ridge; border-width:7px; padding:12px; float:left; background-color:gray\"&gt;\n"; for($x = 0; $x &lt; 5; $x++) { for($y = 0; $y &lt; 5; $y++) { echo "&lt;input type=\"text\" name=\"" . $name . $x . $y . "\" maxlength=\"6\" style=\"width:50px\" value=\""; if($name == "MatrixA") echo "" . $matrixa[$x][$y]; else if($name == "MatrixB") echo "" . $matrixb[$x][$y]; echo "\"&gt;\n"; } echo "&lt;br&gt;\n"; } echo "&lt;/div&gt;\n"; echo "&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;\n"; } loadArrays("MatrixA","MatrixB"); createMatrix("MatrixA"); createMatrix("MatrixB"); ?&gt; &lt;input type="submit" value="Add Matrices" name="add" /&gt; &lt;input type="submit" value="Subtract Matrices" name="subtract" /&gt; &lt;/form&gt; </code></pre> <p>This project is due at midnight so I'd appreciate some help :)</p> <p>Basically the problem is trying to save the values. I am able to load the variables from post data into the arrays using loadArrays() just fine, but the values don't show up AT ALL when I use createMatrix();</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload