cvs: phpdoc /en/language control-structures.xml
| From: | Kalle Sommer Nielsen | Date: | Sun, 31 Aug 2008 00:35:09 +0000 |
| Subject: | cvs: phpdoc /en/language control-structures.xml | ||
| Groups: | php.doc.cvs | ||
| Request: | Send a blank email to doc-cvs+get-2119@lists.php.net to get a copy of this message | ||
kalle Sun Aug 31 00:35:09 2008 UTC
Modified files:
/phpdoc/en/language control-structures.xml
Log:
Add a tip regrading array iteration with for (Thanks for the help Pierre)
http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures.xml?r1=1.165&r2=1.166&diff_format=u
Index: phpdoc/en/language/control-structures.xml
diff -u phpdoc/en/language/control-structures.xml:1.165
phpdoc/en/language/control-structures.xml:1.166
--- phpdoc/en/language/control-structures.xml:1.165 Sun Aug 24 07:26:25 2008
+++ phpdoc/en/language/control-structures.xml Sun Aug 31 00:35:09 2008
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="iso-8859-1"?>
-<!-- $Revision: 1.165 $ -->
+<!-- $Revision: 1.166 $ -->
<chapter xml:id="language.control-structures" xmlns="http://docbook.org/ns/docbook"
xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Control Structures</title>
@@ -524,7 +524,60 @@
endfor;
]]>
</programlisting>
- </informalexample>
+ </informalexample>
+ </para>
+ <simpara>
+ Its a common thing to many users to iterate though arrays like in the
+ example below.
+ </simpara>
+ <para>
+ <informalexample>
+ <programlisting>
+<![CDATA[
+<?php
+/*
+ * This is an array with some data we want to modify
+ * when running though the for loop.
+ */
+$people = Array(
+ Array('name' => 'Kalle', 'salt' => 856412),
+ Array('name' => 'Pierre', 'salt' => 215863)
+ );
+
+for($i = 0; $i < sizeof($people); ++$i)
+{
+ $people[$i]['salt'] = rand(000000, 999999);
+}
+?>
+]]>
+ </programlisting>
+ </informalexample>
+ </para>
+ <simpara>
+ The problem lies in the second for expression. This code can be slow
+ because it has to calculate the size of the array on each iteration.
+ Since the size never change, it can be optimized easily using an
+ intermediate variable to store the size and use in the loop instead
+ of sizeof. The example below illustrates this:
+ </simpara>
+ <para>
+ <informalexample>
+ <programlisting>
+<![CDATA[
+<?php
+$people = Array(
+ Array('name' => 'Kalle', 'salt' => 856412),
+ Array('name' => 'Pierre', 'salt' => 215863)
+ );
+
+for($i = 0, $size = sizeof($people); $i < $size; ++$i)
+{
+ $people[$i]['salt'] = rand(000000, 999999);
+}
+?>
+]]>
+ </programlisting>
+ </informalexample>
</para>
</sect1>