Reprinted from PHP forums:
https://learnku.com/php/t/49583

After doing a lot of code reviews, I often see repeated errors, and here’s how to correct them.

Test whether the array is empty before looping

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

The foreach and array functions (array_*) can handle empty arrays.

  • You don’t need to test it first
  • You can reduce one level of indentation

$items = [];

// ...

foreach ($items as $item) {

// process on $item ...

}

Encapsulate the code content into an if statement summary


function foo(User $user) {

if (!$user->isDisabled()) {

// ...

// long process

// ...

}

}

This is not unique to PHP, but I often run into it. You can reduce the indentation by going back early.

All major methods are at the first indentation level

function foo(User $user) { if ($user->isDisabled()) { return; } / /... // Other code //... }

The isset method is called several times

You may encounter the following situations:

$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 if a variable is defined. PHP provides an isset function that can be used to check for this variable, and this function can take more than one argument at a time, so the following code might be better:

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

The echo and sprintf methods are used together


$name = "John Doe";

echo sprintf('Bonjour %s', $name);

You might want to laugh at this code, but I did write this for a while, and I still see a lot of it! In fact, echo and sprintf do not need to be used together, printf is fully printable.


$name = "John Doe";

printf('Bonjour %s', $name);

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


$items = [

'one_key' => 'John',

'search_key' => 'Jane',

];

if (in_array('search_key', array_keys($items))) {

// process

}

The last error I often see is the combination of in_array and array_keys. All of these can be replaced with array_key_exists.


$items = [

'one_key' => 'John',

'search_key' => 'Jane',

];

if (array_key_exists('search_key', $items)) {

// process

}

We can also use isset to check if the value is not null.


if (isset($items['search_key'])) {

// process

}

For discussion, please visit the professional PHP forum:
https://learnku.com/php/t/49583