DEV Community

Jimmy Klein
Jimmy Klein

Posted on • Edited on

5 bad habits to lose in PHP

I do a lot of code review and I often see the same mistakes. Here's how to correct them.

Test that an array is not empty before loop

$items = [];
// ...
if (count($items) > 0) {
    foreach ($items as $item) {
        // process on $item ...
    }
}
Enter fullscreen mode Exit fullscreen mode

foreach loop or array function (array_*) can handle empty array.

  • No need to test it before
  • One less indentation level
$items = [];
// ...
foreach ($items as $item) {
    // process on $item ...
}
Enter fullscreen mode Exit fullscreen mode

If you want to learn how to code without for/foreach/while loop, I recommend my article on collections (in French).


Encapsulate all the content of a method in an if statement

function foo(User $user) {
    if (!$user->isDisabled()) {
        // ...
        // long process
        // ...
    }
}
Enter fullscreen mode Exit fullscreen mode

This one is not specific to PHP but I see it very often. I have already talk in my article about calisthenics objects and in my article about my minimalist code of reduce indentation level using early return.
All the "useful" body of the function is now at first indentation level

function foo(User $user) {
    if ($user->isDisabled()) {
        return;
    }

    // ...
    // long process
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Call multiple times isset method

$a = null;
$b = null;
$c = null;
// ...

if (!isset($a) || !isset($b) || !isset($c)) {
    throw new Exception("undefined variable");
}

// or

if (isset($a) && isset($b) && isset($c) {
    // process with $a, $b et $c
}

// or 

$items = [];
//...
if (isset($items['user']) && isset($items['user']['id']) {
    // process with $items['user']['id']
}
Enter fullscreen mode Exit fullscreen mode

We often need to check that a variable is defined (and not null). In PHP, we can do this by using isset function. And, magic, it can take multiple parameters !

$a = null;
$b = null;
$c = null;
// ...

if (!isset($a, $b, $c)) {
    throw new Exception("undefined variable");
}

// or

if (isset($a, $b, $c)) {
    // process with $a, $b et $c
}

// or 

$items = [];
//...
if (isset($items['user'], $items['user']['id'])) {
    // process with $items['user']['id']
}
Enter fullscreen mode Exit fullscreen mode

Combine the echo method with sprintf

$name = "John Doe";
echo sprintf('Bonjour %s', $name);
Enter fullscreen mode Exit fullscreen mode

This bit of code may be smiling but I happened to write it a while ago. And I still see it quite a bit! Instead of combining echo andsprintf, we can simply use the printf method.

$name = "John Doe";
printf('Bonjour %s', $name);
Enter fullscreen mode Exit fullscreen mode

Check the presence of a key in an array by combining two methods

$items = [
    'one_key' => 'John',
    'search_key' => 'Jane',
];

if (in_array('search_key', array_keys($items))) {
    // process
}
Enter fullscreen mode Exit fullscreen mode

Last error I see quite often is the joint use of in_array andarray_keys. All of this can be replaced using array_key_exists.

$items = [
    'one_key' => 'John',
    'search_key' => 'Jane',
];

if (array_key_exists('search_key', $items)) {
    // process
}
Enter fullscreen mode Exit fullscreen mode

We can also use isset which also check that the value is not null.

if (isset($items['search_key'])) {
    // process
}
Enter fullscreen mode Exit fullscreen mode

Thank you for reading, and let's stay in touch !

If you liked this article, please share. You can also find me on Twitter/X for more PHP tips.

Top comments (7)

Collapse
 
dmahely profile image
Doaa Mahely

The multiple isset is a good one, thanks

Collapse
 
joshcheek profile image
Josh Cheek

Note that the "early return" is called a "guard clause"

Collapse
 
kushal-niroula profile image
Kushal Niroula

For the fourth one, I rather prefer string interpolation.

echo "Hello {$name}" ;
Collapse
 
klnjmm profile image
Jimmy Klein

String interpolation works to in this case. 👍
I am used to (s)printf when
I want to translate string which contains variables with gettext and also to format float.

Collapse
 
jsn1nj4 profile image
Elliot Derhay

I like string interpolation too whenever I can get away with it.

Collapse
 
marcusatlocalhost profile image
Marcus

String interpolation gets weird if your string contains quotes, though

printf('<a href="%s"></a>',$link);

vs

echo "<a href=\"{$link}\"></a>";

Of course one could write it this way

echo "<a href='{$link}'></a>";
  • but for some reasons I don't like single quotes for html attributes :)

At the end and in this case, whatever works best/is the easiest to write and read. sprintf with many vars is a pain to read.

Collapse
 
pinguinosod profile image
David Cautin • Edited

I don't usually program in PHP anymore but just today I had to do something and I made the multiple isset mistake. Thanks! I learned something new