diff --git a/language/control-structures/for.xml b/language/control-structures/for.xml index b3fe2b350578..9862411e3f02 100644 --- a/language/control-structures/for.xml +++ b/language/control-structures/for.xml @@ -142,97 +142,61 @@ endfor; - It's common for many users to iterate through arrays like in the - example below. + Expressions expr2 and expr3 are + evaluated every iteration. It's advisable to use simple expressions in these + places to avoid performance issues. For example, if the number of iterations + is known in advance, it is better to use a variable instead of a function call + in expr2: - + 'Kalle', 'salt' => 856412), - array('name' => 'Pierre', 'salt' => 215863) -); -for($i = 0; $i < count($people); ++$i) { - $people[$i]['salt'] = random_int(100000, 999999); +$people = ['Kalle', 'Pierre']; + +// Bad practice: calling a function on every iteration +for($i = 0; $i < getIterationCount($people); ++$i) { + $people[$i] .= ' is cool'; } -var_dump($people); -]]> - - &example.outputs.similar; - - - array(2) { - ["name"]=> - string(5) "Kalle" - ["salt"]=> - int(454478) - } - [1]=> - array(2) { - ["name"]=> - string(6) "Pierre" - ["salt"]=> - int(776978) - } + +// Good practice: storing the count in a variable +for($i = 0, $peopleCount = getIterationCount($people); $i < $peopleCount; ++$i) { + $people[$i] .= ' is cool'; } + ]]> - + - The above code can be slow, because the array size is fetched on - every iteration. Since the size never changes, the loop can be easily - optimized by using an intermediate variable to store the size instead - of repeatedly calling count: + In the example above, the function is called on every iteration of the + first loop, even though it always returns the same value. Storing that + value in a variable, as the second loop does, calls the function once. + Note that the number of iterations is then fixed: if the array is + modified inside the loop, the stored value no longer reflects its size. - - - - 'Kalle', 'salt' => 856412), - array('name' => 'Pierre', 'salt' => 215863) -); -for($i = 0, $size = count($people); $i < $size; ++$i) { - $people[$i]['salt'] = random_int(100000, 999999); -} -var_dump($people); -]]> - - &example.outputs.similar; - - - array(2) { - ["name"]=> - string(5) "Kalle" - ["salt"]=> - int(454478) - } - [1]=> - array(2) { - ["name"]=> - string(6) "Pierre" - ["salt"]=> - int(776978) - } -} -]]> - - - + + + The size of an array is stored with the array, which means that + calling the built-in function count does not require + counting the elements and does not cause performance issues. This does not + apply to COUNT_RECURSIVE, which walks the whole array. + Care should also be taken when using count on objects + implementing Countable, as such calls can be + more expensive. + + + + + + The for loop is not the recommended way to + iterate over arrays. The &foreach; loop is specifically + designed for this purpose and is usually more convenient. + +