⊗ppPmLpCdg 129 of 447 menu

Tips for Writing Loop Code in PHP

As you learn the language, the complexity of your programs increases. It's time to talk about how to write code correctly so that it does what you intended. I will give you a good methodology.

Suppose you have a task of sufficient complexity, for the implementation of which you need to write a certain number of lines of code.

The wrong approach is to try to write the entire solution code at once, and then start checking it. In this case, there is a high probability that nothing will work for you, and you will have to look for an error in a large amount of code.

The correct approach is to break the task into small elementary steps, which you will implement and immediately check for correctness. In this case, even if you make a mistake somewhere, you will immediately notice the problem and fix it.

Let's try it in practice. For example, let's say you are given an array with numbers:

<?php $arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; ?>

Suppose your task is to take from this array those elements that are divisible by 3 and find their sum.

As a first small step, I would suggest simply iterating through the array elements with a loop and outputting them to the screen. Let's do this and make sure that everything works:

<?php foreach ($arr as $elem) { echo $elem; } ?>

Now let's separate those elements that are divisible by 3. Let's output them and make sure that we get the correct elements:

<?php foreach ($arr as $elem) { if ($elem % 3 === 0) { echo $elem; // outputs 3, 6, 9 } } ?>

Now the next step we can find the sum of the desired elements:

<?php $sum = 0; foreach ($arr as $elem) { if ($elem % 3 === 0) { $sum += $elem; } } var_dump($sum); ?>

Given an array:

<?php $arr = [10, 20, 30, 40, 21, 32, 51]; ?>

Take from this array those elements whose first digit is 1 or 2, and find their sum.

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