Common PHP Code Review Mistakes and How to Fix Them

After extensive code reviews, this article highlights frequent PHP mistakes—such as testing empty arrays before loops, unnecessary nesting, repeated isset calls, misuse of echo with sprintf, and inefficient array key checks—and provides concise refactored examples to improve readability and performance.

php Courses
php Courses
php Courses
Common PHP Code Review Mistakes and How to Fix Them

After doing many code reviews, I often see repeated errors; here are ways to correct them.

1. Test if array is empty before looping

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

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

No need to test beforehand.

Reduces one level of indentation.

2. Wrap code in a single if statement

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

Use early return to reduce nesting:

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

3. Repeated calls to isset

Instead of checking each variable separately, isset can accept multiple arguments.

$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 and $c
}

For nested arrays:

if (isset($items['user'], $items['user']['id'])) {
    // process with $items['user']['id']
}

4. Using echo with sprintf

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

Prefer printf for direct output:

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

5. Checking for a key in an array

$items = [
    'one_key' => 'John',
    'search_key' => 'Jane',
];
if (in_array('search_key', array_keys($items))) {
    // process
}

Replace the in_array + array_keys pattern with array_key_exists or isset:

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

// or
if (isset($items['search_key'])) {
    // process
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

programmingCode reviewPHP
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.