<?xml version="1.0" encoding="windows-1252"?>
<node id="72634" title="Re: NEWBIE Brain Teaser" created="2001-04-15 03:41:23" updated="2005-07-19 14:08:39">
<type id="11">
note</type>
<author id="66801">
nysus</author>
<data>
<field name="doctext">
Now that the cat's out of the bag, I'll share the explanation I had written up...a bit more long winded:
&lt;p&gt;
&lt;b&gt;HOW THE CODE WORKS&lt;/b&gt;&lt;p&gt;
So what's going on here?  At first glance, this bit of code seems pretty straightforward. Line 1 assigns numbers 1 thru 5 to the first 5 elements of the &lt;code&gt;@list&lt;/code&gt; array.  Lines 3-6 do nothing but declare variables.  The &lt;code&gt;foreach&lt;/code&gt; loop starting on line 8 assigns each element of &lt;code&gt;@list&lt;/code&gt; to &lt;code&gt;$each&lt;/code&gt; and multiplies the contents of &lt;code&gt;$each&lt;/code&gt; by two.  It then assigns each &lt;code&gt;$each&lt;/code&gt; to an element of the &lt;code&gt;@newlist&lt;/code&gt; array.  Finally, the &lt;code&gt;for&lt;/code&gt; loop starting on line 14 simply steps through each element of both the &lt;code&gt;@newlist&lt;/code&gt; and &lt;code&gt;@list&lt;/code&gt; arrays simultaneously and subtracts one array from the other.  You would expect the first iteration of the &lt;code&gt;for&lt;/code&gt; loop to be &lt;i&gt;2-1&lt;/i&gt; yielding "1", the next iteration to give &lt;i&gt;4-2&lt;/i&gt; yielding "2", and so on.  So what's the problem here?&lt;p&gt;
The answer lies in the first statement of the &lt;code&gt;foreach&lt;/code&gt; block, &lt;code&gt;$each *= 2;&lt;/code&gt;.  What happens is that the &lt;code&gt;@list&lt;/code&gt; array gets &lt;b&gt;aliased&lt;/b&gt; through the &lt;code&gt;$each&lt;/code&gt; variable.  What does this mean?  It means that whatever you do to the &lt;code&gt;$each&lt;/code&gt; variable in the &lt;code&gt;foreach&lt;/code&gt; loop, you also do to the corresponding element of the &lt;code&gt;@list&lt;/code&gt; array.  So, for example, when &lt;code&gt;$each&lt;/code&gt; is equals "3" and it gets multiplied by "2", the third element of &lt;code&gt;@list&lt;/code&gt; gets multiplied by "2", too, setting it's value to "6".  And there you have the reason why the output of this code is nothing but 5 zeroes!</field>
<field name="root_node">
72605</field>
<field name="parent_node">
72605</field>
</data>
</node>
