diff --git a/language/control-structures/for.xml b/language/control-structures/for.xml index b3fe2b350578..79bf1a10ce7a 100644 --- a/language/control-structures/for.xml +++ b/language/control-structures/for.xml @@ -142,97 +142,60 @@ 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 + In the example above, the invoked function always returns the same value. + 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: + of repeatedly calling the same function. An added benefit is that the + number of iterations is now constant, which helps avoid bugs when the + array is modified during the loop. - - - - '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. However, care + should 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. + +