Tips & Tricks for writing better PHP code


PHP is one of the widely used Server Side Scripting Language. It’s easy to learn PHP but it’s tricky to use it correctly. Let’s see some of the tips & tricks for writing better PHP code.

Variable Validation
Consider a scenario where we have to find array count or string length of a variable and we have to handle all kinds of errors and warnings.This sounds very simple but most of the newbies can’t complete it (with my experience) because they don’t know how to write quality code.
Let’s calculate length of a string

Let’s check for array count & loop through the each values

Return type of inbuilt function
PHP comes with so much of inbuilt funtions and of course it’s important to use them but always remember their “return type”. Let’s understand this with an interview of fresher which took some days ago.
Me: Can u tell me return type of date(“Y-m-d”) ?
Fresher: String
Me: Can u tell me return type of date(“YW”) ?
Fresher: Integer
And that’s the problem, for newbies return type means what they see as output, in this case if fresher saw 2016-01-02 then return type of date was string and if it was 201601 the it is integer, which is wrong.Return type of a function never varies with the output.

Free memory
Memory is a very important aspect of any application. PHP is not so good with it’s memory management by itself but we can take care of it with some simple tips as follows:

  • Unset the values when after it’s use.
  • while running an infinite loop (like in background services) always use gc_collect_cycles, this will collect any garbage cycles, thus reducing memory

Limit memory
It’s always good practice to limit memory of a php script.Say we have to set memory limit to 100Mb then we should write is as ini_set(‘memory_limit’, ‘100M’);

Follow MVC approach
Models deals with database(s), Controller contains logic and Views contains front-end design.It is the best approach to maintain your code and separate logic with design. MVC provides a single file to handle your incoming request, which makes it very easily to handle, debug and maintain requests

Use arrays
I prefer arrays over a simple variable just because it’s easy to maintain and perform operations on array than a single variable. But don’t overuse it, just use it wisely.

I hope these tips and tricks will help you to write more robust code.