5 bad habits to lose in PHP
Tags: php, codequality
Published: 2020-06-13 15:33:53

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

```php
$items = [];
// ...
if (count($items) > 0) {
    foreach ($items as $item) {
        // process on $item ...
    }
}
```


`foreach` loop or array function (`array_*`) can handle empty array.
* No need to test it before
* One less indentation level

```php
$items = [];
// ...
foreach ($items as $item) {
    // process on $item ...
}
```

*If you want to learn how to code without `for`/`foreach`/`while` loop, I recommend [my article on collections](https://www.jimmyklein.fr/refactoring-to-collections/) (in French).*

---

## Encapsulate all the content of a method in an if statement

```php
function foo(User $user) {
    if (!$user->isDisabled()) {
        // ...
        // long process
        // ...
    }
}
```

This one is not specific to PHP but I see it very often. I have already talk in [my article about calisthenics objects](https://www.jimmyklein.fr/les-objets-calisthenics/) and in [my article about my minimalist code](https://dev.to/klnjmm/less-is-now-518a) of reduce indentation level using **early return**.
All the "useful" body of the function is now at **first indentation level**

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

    // ...
    // long process
    // ...
}
```

---

## Call multiple times isset method

```php
$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']
}
```

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** !

```php
$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']
}
```

---

## Combine the echo method with sprintf

```php
$name = "John Doe";
echo sprintf('Bonjour %s', $name);
```

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` and` sprintf`, we can simply use the `printf` method.

```php
$name = "John Doe";
printf('Bonjour %s', $name);
```

---

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

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

if (in_array('search_key', array_keys($items))) {
    // process
}
```

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

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

if (array_key_exists('search_key', $items)) {
    // process
}
```

We can also use `isset` which also check that the value is not `null`.
```php 
if (isset($items['search_key'])) {
    // process
}
```

---

## 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](https://twitter.com/enjimmyklein) for more PHP tips.