5 bad habits to lose in PHP
Jimmy Klein

Jimmy Klein @klnjmm

About: Hi, it's Jimmy 👋, PHP 🐘 developper, guitarist 🤘 and minimalist apprentice. I help developers progress in PHP.

Location:
Macon, France
Joined:
Jan 19, 2018

5 bad habits to lose in PHP

Publish Date: Jun 13 '20
109 7

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.

Comments 7 total

  • Kushal Niroula
    Kushal NiroulaJun 13, 2020

    For the fourth one, I rather prefer string interpolation.

    echo "Hello {$name}" ;
    
    • Elliot Derhay
      Elliot DerhayJun 13, 2020

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

      • Marcus
        MarcusJun 14, 2020

        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.

    • Jimmy Klein
      Jimmy KleinJun 13, 2020

      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.

  • David Cautin
    David CautinJun 15, 2020

    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

  • Josh Cheek
    Josh CheekJun 15, 2020

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

  • Doaa Mahely
    Doaa MahelyJun 15, 2020

    The multiple isset is a good one, thanks

Add comment