Add a tip regrading array iteration with for (Thanks for the help Pierre)

git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@265700 c90b9560-bf6c-de11-be94-00142212c4b1
This commit is contained in:
Kalle Sommer Nielsen 2008-08-31 00:35:09 +00:00
parent 9c862a24c1
commit a25ea24b7e

View file

@ -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 @@ for (expr1; expr2; expr3):
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>