⊗ppSpOtEI 76 of 83 menu

Optimization of Unnecessary Loop Iterations in PHP

In the following code, a certain programmer checks if the array contains the number 3:

<?php $arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; $exists = false; foreach ($arr as $elem) { if ($elem == 3) { $exists = true; } } var_dump($exists); ?>

What's wrong with their solution? It seems like no unnecessary operations are performed in the loop. The problem, however, is that after it's determined that the number 3 is in the array - the loop still continues to run until the end of the array.

The most inefficient scenario would be if the number 3 is found somewhere at the beginning of the array, and the array itself has a length of, say, 1000 elements. That would result in a thousand useless extra loop iterations! Not optimal.

Let's optimize the code by stopping the loop in time:

<?php $arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; $exists = false; foreach ($arr as $elem) { if ($elem == 3) { $exists = true; break; } } var_dump($exists); ?>

The following code calculates how many array elements need to be added for the sum to become greater than 10. Perform optimization:

<?php $arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; $sum = 0; $i = 1; foreach ($arr as $elem) { $sum += $elem; if ($sum <= 10) { $i++; } } echo $i; ?>

The following code outputs even numbers from a given range. Perform optimization:

<?php for ($i = 0; $i <= 100; $i++) { if ($i % 2 === 0) { echo $i; } } ?>

The following code outputs numbers divisible by both 2 and 3. Perform optimization:

<?php for ($i = 0; $i <= 100; $i++) { if ($i % 2 === 0 and $i % 3 === 0) { echo $i; } } ?>
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline