Home > Article > Backend Development > 10 PHP programming tips, 10 PHP tips_PHP tutorial
1. This situation will be used when writing a program, such as rounding a number all. Many people will write like this:
Copy code The code is as follows:
input a
if a - int(a) >= 0.5 then
a = a 1
end if
In fact, this judgment statement can be written using a very simple expression
Copy code The code is as follows:
a = fix(a sgn(a) *0.5)
Writing in php:
Copy code The code is as follows:
$a = intval($a 0.5 * ($a >0 ? 1 : -1) );
Analysis:
Suppose a is 4.4, then a 0.5 = 4.9 will be 4 after intval(). Suppose a is 4.6 a 0.5=5.1, then intval() will be 5 after that, so rounding is achieved.
A positive number is 0.5, and a negative number is -0.5.
The same goes for rounding to 2 decimal places.
Copy code The code is as follows:
$a = intval(a * 100 0.5 * ($a >0 ? 1 : -1) ) /100.
2. Find the value of a-b. If it is less than 0, take 0. You can write city
Copy code The code is as follows:
$result = max(0,$a-$b);
3. When importing data, you can choose to use csv format. PHP is very convenient to process getcsv.
4. str_replace() is more efficient than regular expressions in replacing strings. In fact, according to Making the Web, str_replace() is 61% more efficient than regular expressions like ereg_replace() and preg_replace().
5. if($a==true) if($a)
6. It is faster to use isset to determine whether variables and elements exist
7. Try to use ternary arithmetic
8. Write if line statements appropriately. Use return statements appropriately within functions to reduce branches
9. Use memcache mogodb, etc. to reduce the burden on programs and databases
10. Temporary data can be recorded using sqllite