⊗ppSpOtRO 72 of 83 menu

Optimization of Repeated Operations in PHP

Often, beginner programmers thoughtlessly call the same function multiple times, wasting resources.

Let's look at an example. Consider the following code:

<?php $arr = [1, 2, 3, 4, 5]; if (count($arr) >= 1 and count($arr) <= 3) { } ?>

What's wrong with this code? The fact is that we do the same thing twice - calculate the length of the array using count($arr). This operation takes time and it is advisable to perform it once, assign the result to a variable, and then use this variable where needed, like this:

<?php $arr = [1, 2, 3, 4, 5]; $len = count($arr); if ($len >= 1 and $len <= 3) { } ?>

Optimize the code below:

<?php if (date('Y') >= 2018 and date('Y') <= 2020) { echo 'year ' . date('Y') . ' is suitable'; } else { echo 'year ' . date('Y') . ' is not suitable'; } ?>

Optimize the code below:

<?php $password = 'abcde'; if (strlen($password) >= 2 and strlen($password) <= 10) { echo 'password length is acceptable'; } else { echo 'invalid password length'; } ?>
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