Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem lies in your new_tr() function:</p> <pre><code>function new_tr(&amp;$table, $class) { $tr = array('class' =&gt; $class, 'td' =&gt; array()); $table['tr'][] = $tr; return $tr; } </code></pre> <p>The way you created $tr here, means it's a regular variable that will be copied when necessary. It does get added to $table, because that is a reference.</p> <p>PHP uses copy on write, so when the code returns the $tr you add to $table and the $tr you return are actually still one and the same variable. </p> <p>But when you go and write to it in new_td(), PHP determines it needs to make a copy because it's not a reference to something. So at this point the $tr in your calling script and the corresponding $tr in your $table array are actually two separate variables/values. So new_td() got a copy of that $tr, instead of the exact same one you created in new_tr(). </p> <p>To fix this, you need to make the new_tr function actually create a reference to the TR and also return the TR it created as a reference:</p> <pre><code>// Return the created TR as a reference by adding the ampersand here. function &amp;new_tr(&amp;$table, $class) { $tr = array('class' =&gt; $class, 'td' =&gt; array()); // The TR in $table needs to be a reference to the value we're returning // because we want to modify this exact variable instead of some copy. $table['tr'][] =&amp; $tr; return $tr; } </code></pre> <p>Now when you run it and your code calls new_td($tr), it is actually modifying the variable that you added to $table:</p> <pre><code>$table = new_table('admin whoami'); $tr =&amp; new_tr($table, 'head'); new_td($tr, 'field', 'Field'); // EDIT: Note how you need to create a reference here aswell. This is to // make $tr a reference to the return value of new_tr() instead of a value copy. $tr =&amp; new_tr($table, 'body'); echo '--- table ---'.chr(10); var_dump($table); </code></pre> <p>results in:</p> <pre><code>--- table --- array(2) { ["class"]=&gt; string(12) "admin whoami" ["tr"]=&gt; array(2) { [0]=&gt; array(2) { ["class"]=&gt; string(4) "head" ["td"]=&gt; array(1) { [0]=&gt; array(2) { ["class"]=&gt; string(5) "field" ["content"]=&gt; string(5) "Field" } } } [1]=&gt; &amp;array(2) { ["class"]=&gt; string(4) "body" ["td"]=&gt; array(0) { } } } } </code></pre>
 

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