The PHP language is known for being simple and easy to learn, but some beginners often write low-performance PHP code, which can seriously affect the operating efficiency of the entire system. In this article, we have collected some PHP programming tips and optimization techniques for everyone. We hope PHP beginners will carefully read the following editing tips and develop good PHP programming habits!

63 PHP Programming Tips
- 1. Use as many PHP built-in functions as possible.
- 2. Use
echoinstead ofprint, and useechomultiple parameters (translator's note: meaning commas instead of periods) instead of string concatenation, for example
echo $str1,$str2;
3. Don't break methods down too much; think carefully about which code you actually intend to reuse.4. During executionfor4. Before executinga loop, determine the maximum number of iterations; don't calculate the maximum on every iteration.5. Unset unused variables, especially large arrays, to free up memory.
7、 $row['id']The efficiency of$row[id]is 7 times that of8. Use full paths when including files; it will take less time to resolve operating system paths.9. If you want to know when the script started executing (translator's note: i.e., when the server receives the client request), use$_SERVER['REQUEST_TIME']is better thantime()。10. Functions can replace regular expressions to accomplish the same functionality.str_replacefunction is faster thanpreg_replacefunction, butstrtrthe efficiency of the function isstr_replacefour times that of the function.11. Pay attention to code indentation.12. If a string replacement function can accept arrays or characters as parameters, and the parameter length is not too long, consider writing an additional replacement code segment so that each time a single character is passed as a parameter, rather than writing just one line of code that accepts an array as the search and replace parameter.13. Use a switch statement (translator's note: i.e.,switch case) instead of multipleif,else ifstatements.14. Using @ to suppress error messages is very inefficient.15. Enable Apache's mod_deflate module.16. Database connections should be closed when they are no longer used.18. Error messages are expensive.19. Try not to use functions in for loops, for examplefor ($x=0; $x < count($array); $x)count() is called on every iteration.20. Incrementing a local variable inside a method is the fastest. It is almost the same speed as calling a local variable inside a function.21. Incrementing a global variable is 2 times slower than incrementing a local variable.22. Incrementing an object property (e.g.,$this->prop++) is 3 times slower than incrementing a local variable.23. Incrementing an undefined local variable is 9 to 10 times slower than incrementing a predefined local variable.24. Merely defining a local variable without calling it in a function will also slow down the speed (to a degree equivalent to incrementing a local variable). PHP probably checks to see if a global variable exists.25. Method calls appear to be unrelated to the number of methods defined in the class, because I added 10 methods (both before and after testing the method), but performance did not change.26. Methods in derived classes run faster than the same methods defined in the base class.27. Calling an empty function with one parameter takes about the same time as performing 7 to 8 local variable increments. A similar method call takes close to 15 local variable increments.28. Use single quotes instead of double quotes to enclose strings; this is faster. Because PHP searches for variables in strings enclosed by double quotes, but not in single quotes. Of course, you can only do this when you don't need to include variables in the string.29. When usingechoto output multiple strings, use commas instead of periods to separate strings; it is faster.30. Apache takes 2 to 10 times longer to parse a PHP script than to parse a static HTML page. Try to use static HTML pages more and scripts less.31. Unless scripts can be cached, they will be recompiled every time they are called. Introducing a PHP caching mechanism can usually improve performance by 25% to 100%, eliminating compilation overhead.32. Do caching as much as possible; you can use memcached. memcached is a high-performance, distributed memory object caching system that can be used to speed up dynamic web applications and reduce database load. Caching opcode is very useful, so scripts don't have to be recompiled for every request.33. When manipulating strings and needing to check whether their length meets certain requirements, you would naturally usestrlen()function. This function executes fairly quickly because it doesn't do any calculation, it just returns the known string length stored in the zval structure (C's built-in data structure used to store PHP variables). However, becausestrlen()is a function, it will be somewhat slow, because a function call goes through many steps, such as lowercasing (translator's note: meaning the function name is lowercased; PHP does not distinguish between uppercase and lowercase function names), hash lookup, and these execute along with the called function. In some cases, you can useisset()technique to speed up the execution of your code.
if (strlen($foo) < 5) { echo "Foo is too short"; }
if (!isset($foo{5})) { echo "Foo is too short"; }
34. If you can define a class method asstatic, try to define it asstatic, its speed will increase by nearly 4 times.35. Don't usearray_key_exists, useissetto check whether a key exists in an array.36. Avoid using__set,__getmagic methods such as37. Useinclude/requireinstead ofinclude_once/require_once, and try to use absolute paths.38. Don't putcount/strlen/sizeofetc. intoforloop condition statements.39. Try to useforeachinstead offor/while40. When a string contains variables, use double quotes instead of single quotes, e.g.
echo "hi, $name, nice to meet you";
41. Usefreadto read small files, usefile_get_contentsto read large files, and usefseekfor very large files.ip2long()andlong2ip()42. Usefunction to convert an IP address into an integer for storage. This makes it simpler to calculate whether a particular address is within a range, and also speeds up searching and sorting.checkdnsrr()43. When validating an email address, usefunction to verify whether the domain exists. This built-in function can confirm that the specified domain can be resolved to an IP address.mysql_*44. Consider abandoningmysqli_*series functions in favor of the improvedseries functions.45. Learn to love the ternary operator.46. If you feel there is a reusable part in your project, check whether PEAR already has it before writing the next line of code. This online repository contains more than 400 reusable program fragments that can be immediately used in your program. Unless your project is truly extraordinary, you can always find a PEAR package to help you save time.highlight_file()47. Useto automatically print formatted, beautiful source code.error_reporting(0)48. Usephp.inifunction to prevent users from seeing potentially sensitive error information. Ideally, on a production server this should be completely disabled inerror_reporting(0)
. But if you are using a shared web server, you don't have your own php.ini file, so in that case your best choice is to addgzcompress()andgzuncompress()49. Before storing very large strings in the web database, useto explicitly compress/decompress strings.50. Use the method of passing parameters by "reference" to get multiple return values from a function.magic_quotes51. Fully understand the dangers of "magic quotes" and SQL injection. The simplest way to prevent SQL injection: in php.ini, setmysql_real_escape_string()to On, and usefunction to escape.52. Database connections should be closed when they are no longer used; do not use persistent connections.
53. For global variables, unset() them as soon as you are done using them.htmlentities()orhtmlspecialchars()54. Don't trust user-submitted data; always use
to escape it first.$i55. When performing$i++increment or decrement on a variable,++$iis slower than++$i. This difference is specific to PHP and does not apply to other languages, so please don't modify your C or Java code and expect it to become faster immediately; it won't.$i++is faster because it requires only 3 instructions (opcodes),requires 4 instructions. Post-increment actually creates a temporary variable, which is then incremented. Pre-increment directly increments the original value.56. Not everything must be object-oriented (OOP). OOP often has high overhead; every method and object call consumes a lot of memory.57. If there are many time-consuming functions in your code, you can consider implementing them as C extensions.59. mod_zip can be used as an Apache module to compress your data on the fly, and can reduce data transfer volume by 80%.60. Try to minimize file operations as much as possible, although PHP's file operation efficiency is not low either.61. OptimizationSelect SQLSentence, proceed as little as possible when possible.Insert、UpdateOperation62. Do not declare variables inside loops, especially large variables: objects (This doesn't seem to be a concern only in PHP, right?)63. Try to avoid nested loop assignment for multidimensional arrays.
64、……
Related Resources