Some Tips For PHP developers

Tips for PHP developers to write shorter and high-performance code

Image for post
Image for post

I’ve frequently seen developers make a common mistake in ‘for’ loops in their PHP projects. As an example:

At the first glimpse, this code looks ok, but there is an issue with the performance! In each iteration, the ‘count’ function will be executed and if you are having a large array it will cause a performance issue.

To fix this issue, you can easily calculate the count of the array before ‘for’ or inside for(). Have a look at this code:

This function is too long, let's reduce it to just one line!

We could just return the condition here!

return $age >= 15 && $age <= 24;

The ‘strpos’ method is a little bit tricky, it returns the position of the needle. Imagine your needle is in the first position what will the function return? Yes, It will return 0, but what happens when it cannot find your needle? It will return false!

0 and False are the same, you need to control the value and type both.

// This if condition not work because strpos() returns 0 and 0 is false
if (strpos('Foo Bar Baz', 'F')) {
echo 'Found';
// This will work properly.
if (strpos('Foo Bar Baz', 'F') !== false) {
echo 'Found';

In PHP 8, there is a new function str_contains() which returns True and False :)

Backend Developer, Flexitarian, Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store