From a25ea24b7e881feec954aaffa4a25004cbce769d Mon Sep 17 00:00:00 2001 From: Kalle Sommer Nielsen Date: Sun, 31 Aug 2008 00:35:09 +0000 Subject: [PATCH] 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 --- language/control-structures.xml | 57 +++++++++++++++++++++++++++++++-- 1 file changed, 55 insertions(+), 2 deletions(-) diff --git a/language/control-structures.xml b/language/control-structures.xml index f31927662c..9be17d3bfb 100644 --- a/language/control-structures.xml +++ b/language/control-structures.xml @@ -1,5 +1,5 @@ - + Control Structures @@ -524,7 +524,60 @@ for (expr1; expr2; expr3): endfor; ]]> - + + + + Its a common thing to many users to iterate though arrays like in the + example below. + + + + + 'Kalle', 'salt' => 856412), + Array('name' => 'Pierre', 'salt' => 215863) + ); + +for($i = 0; $i < sizeof($people); ++$i) +{ + $people[$i]['salt'] = rand(000000, 999999); +} +?> +]]> + + + + + 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: + + + + + 'Kalle', 'salt' => 856412), + Array('name' => 'Pierre', 'salt' => 215863) + ); + +for($i = 0, $size = sizeof($people); $i < $size; ++$i) +{ + $people[$i]['salt'] = rand(000000, 999999); +} +?> +]]> + +