Home >Backend Development >PHP Tutorial >10 PHP programming tips, 10 PHP tips_PHP tutorial

10 PHP programming tips, 10 PHP tips_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 09:47:12920browse

10 PHP programming tips, 10 PHP tips

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1028303.htmlTechArticle10 PHP programming tips, 10 PHP tips 1. This situation will be used when writing programs , such as rounding a number. Many people will write like this: Copy code Code...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn