DEV Community

Codearea
Codearea

Posted on

10 PHP Tricks That Can Save You From Weird Bugs

PHP looks simple when you first start using it.

You write some code, refresh the page, and hopefully everything works. 😄

But after working with PHP for a while, you start discovering small behaviors that are not always obvious. Some of them can cause confusing bugs, while others can make your code shorter and cleaner.

In this article, let's look at some useful PHP tricks and behaviors that every PHP developer should know.


1. == and === Are Not the Same

This is probably one of the most important PHP details to understand.

PHP has two common comparison operators:

== 
===
Enter fullscreen mode Exit fullscreen mode

The first one compares values, while the second one compares both value and type.

For example:

var_dump(5 == "5");
Enter fullscreen mode Exit fullscreen mode

Output:

bool(true)
Enter fullscreen mode Exit fullscreen mode

PHP considers the values equal after type conversion.

But:

var_dump(5 === "5");
Enter fullscreen mode Exit fullscreen mode

Output:

bool(false)
Enter fullscreen mode Exit fullscreen mode

Why?

Because:

5
Enter fullscreen mode Exit fullscreen mode

is an integer, while:

"5"
Enter fullscreen mode Exit fullscreen mode

is a string.

My recommendation

In most cases, prefer === and !==.

It makes your code more predictable and can prevent unexpected type conversions.

if ($userId === 10) {
    echo "Correct user";
}
Enter fullscreen mode Exit fullscreen mode

2. The Weirdness of 0, "0", and false

PHP has several values that can behave like false in certain situations.

For example:

$value = 0;

if (!$value) {
    echo "This is considered false";
}
Enter fullscreen mode Exit fullscreen mode

The same kind of behavior can happen with:

false
0
""
"0"
null
[]
Enter fullscreen mode Exit fullscreen mode

This can become a problem if you are checking whether a value actually exists.

For example:

$id = 0;

if (!$id) {
    echo "ID does not exist";
}
Enter fullscreen mode Exit fullscreen mode

Maybe 0 is actually a valid value in your application.

In situations like this, be more specific:

if ($id === null) {
    echo "ID is missing";
}
Enter fullscreen mode Exit fullscreen mode

Don't just ask PHP whether something is "truthy" when you actually care about a specific value.


3. The Null Coalescing Operator ??

This little operator is incredibly useful.

Imagine you want to get a username from an array:

$username = $_GET['username'];
Enter fullscreen mode Exit fullscreen mode

If username doesn't exist, PHP can complain about an undefined array key.

Instead, you can use:

$username = $_GET['username'] ?? 'Guest';
Enter fullscreen mode Exit fullscreen mode

Now PHP basically says:

"If username exists, use it. Otherwise, use Guest."

For example:

echo $username;
Enter fullscreen mode Exit fullscreen mode

If the URL doesn't contain a username, the result will be:

Guest
Enter fullscreen mode Exit fullscreen mode

You can also chain it:

$name = $user['name'] ?? $user['username'] ?? 'Guest';
Enter fullscreen mode Exit fullscreen mode

This is one of those small PHP features that you will probably use all the time.


4. ?? Is Different From ?:

These two operators can look similar, but they have different purposes.

Null coalescing

$name = $user['name'] ?? 'Guest';
Enter fullscreen mode Exit fullscreen mode

This mainly checks whether the value exists and is not null.

Ternary

$name = $user['name'] ? $user['name'] : 'Guest';
Enter fullscreen mode Exit fullscreen mode

This checks whether the value is truthy.

That means values such as "", 0, or false can produce different results.

There is also a shorter ternary syntax:

$name = $user['name'] ?: 'Guest';
Enter fullscreen mode Exit fullscreen mode

So don't automatically replace one with the other. Understand what you actually want to check.


5. You Can Swap Variables Without a Temporary Variable

In some languages, you might write:

$temp = $a;
$a = $b;
$b = $temp;
Enter fullscreen mode Exit fullscreen mode

In PHP, you can use array destructuring:

[$a, $b] = [$b, $a];
Enter fullscreen mode Exit fullscreen mode

For example:

$a = 10;
$b = 20;

[$a, $b] = [$b, $a];

echo $a;
echo $b;
Enter fullscreen mode Exit fullscreen mode

Now:

20
10
Enter fullscreen mode Exit fullscreen mode

It's a small trick, but it can make certain code much cleaner.


6. array_map() Can Make Repetitive Code Cleaner

Suppose you have:

$numbers = [1, 2, 3, 4, 5];
Enter fullscreen mode Exit fullscreen mode

And you want to double every number.

You could use a loop:

$result = [];

foreach ($numbers as $number) {
    $result[] = $number * 2;
}
Enter fullscreen mode Exit fullscreen mode

Or you can use:

$result = array_map(
    fn($number) => $number * 2,
    $numbers
);
Enter fullscreen mode Exit fullscreen mode

Now $result contains:

[2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

This can be especially useful when transforming data from an API, database, or another source.


7. You Can Use match Instead of a Huge switch

Modern PHP gives us match.

Instead of:

switch ($status) {
    case 'pending':
        $message = 'Waiting';
        break;

    case 'success':
        $message = 'Completed';
        break;

    case 'failed':
        $message = 'Something went wrong';
        break;

    default:
        $message = 'Unknown';
}
Enter fullscreen mode Exit fullscreen mode

You can write:

$message = match ($status) {
    'pending' => 'Waiting',
    'success' => 'Completed',
    'failed' => 'Something went wrong',
    default => 'Unknown',
};
Enter fullscreen mode Exit fullscreen mode

This is shorter and easier to read.

One important detail: match uses strict comparison.

So types matter.

That's another reason understanding === is important.


8. PHP Strings Can Behave Differently With + and .

Here's a classic beginner mistake.

If you want to concatenate strings in PHP, use:

.
Enter fullscreen mode Exit fullscreen mode

For example:

$name = "Alex";

echo "Hello " . $name;
Enter fullscreen mode Exit fullscreen mode

Output:

Hello Alex
Enter fullscreen mode Exit fullscreen mode

Don't use:

echo "Hello " + $name;
Enter fullscreen mode Exit fullscreen mode

The + operator is for arithmetic.

The . operator is for string concatenation.

This is a small difference, but forgetting it can lead to very confusing results.


9. empty() Has a Surprising Behavior

Consider:

$value = "0";

if (empty($value)) {
    echo "Empty";
}
Enter fullscreen mode Exit fullscreen mode

You might expect "0" to be considered a real string.

But PHP considers "0" empty for the purposes of empty().

This is why you should be careful when using:

empty()
Enter fullscreen mode Exit fullscreen mode

If "0" is a valid value in your application, a simple empty() check may not express what you actually mean.

Sometimes an explicit check is much clearer:

if ($value === '') {
    echo "Empty string";
}
Enter fullscreen mode Exit fullscreen mode

The more precise your condition is, the fewer surprises you'll have later.


10. isset() and array_key_exists() Are Different

This is another useful one when working with arrays.

Suppose:

$data = [
    'name' => null
];
Enter fullscreen mode Exit fullscreen mode

Now:

var_dump(isset($data['name']));
Enter fullscreen mode Exit fullscreen mode

returns:

bool(false)
Enter fullscreen mode Exit fullscreen mode

Why?

Because isset() returns false when the value is null.

But:

var_dump(array_key_exists('name', $data));
Enter fullscreen mode Exit fullscreen mode

returns:

bool(true)
Enter fullscreen mode Exit fullscreen mode

The key actually exists. Its value is simply null.

So remember:

isset()
Enter fullscreen mode Exit fullscreen mode

asks:

"Does this value exist and is it not null?"

While:

array_key_exists()
Enter fullscreen mode Exit fullscreen mode

asks:

"Does this key exist in the array?"

That difference can matter a lot when processing API responses or database data.


Bonus Trick: The Spread Operator

You can use ... to unpack arrays.

For example:

$first = [1, 2, 3];
$second = [4, 5, 6];

$result = [...$first, ...$second];

print_r($result);
Enter fullscreen mode Exit fullscreen mode

Result:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)
Enter fullscreen mode Exit fullscreen mode

You can also use it when passing arguments to functions.

$numbers = [10, 20, 30];

function add($a, $b, $c) {
    return $a + $b + $c;
}

echo add(...$numbers);
Enter fullscreen mode Exit fullscreen mode

Output:

60
Enter fullscreen mode Exit fullscreen mode

Pretty handy, right?


One More Important Tip: Don't Make PHP "Magic"

PHP gives us a lot of shortcuts.

That's great, but shortcuts should make code easier to understand, not harder.

For example, this:

$name = $user['name'] ?? 'Guest';
Enter fullscreen mode Exit fullscreen mode

is great when you understand what it does.

But if you start combining many operators into one giant expression:

$result = $a ?? $b ?: $c && $d ? $e : $f;
Enter fullscreen mode Exit fullscreen mode

you may save a few lines but make your future self very unhappy. 😅

Sometimes this is better:

if ($a !== null) {
    $result = $a;
} elseif ($b) {
    $result = $c;
} else {
    $result = $f;
}
Enter fullscreen mode Exit fullscreen mode

Readable code is usually better than clever code.


Final Thoughts

PHP has many small features that look simple but can behave differently than you might expect.

The most useful ones to remember from this article are:

  • Prefer === when you need strict comparison.
  • Be careful with PHP's truthy and falsy values.
  • Use ?? when you need a fallback for missing or null values.
  • Remember that . concatenates strings.
  • Understand the difference between isset() and array_key_exists().
  • Use match when it makes conditional logic cleaner.
  • Don't be afraid to use array_map() and the spread operator.
  • Avoid clever code when a simple solution is easier to understand.

And honestly, these little details are often what separate "I can write PHP" from "I can maintain a PHP project without constantly fighting weird bugs." 😄

If you're looking for more programming resources and developer-focused content, you can also check out CodeCan.net for more useful development resources.

What is your favorite PHP trick or "weird PHP behavior"? Share it in the comments. I'd love to see which ones have surprised other PHP developers.

Top comments (1)

Collapse
 
merbayerp profile image
Mustafa ERBAY

isset() vs array_key_exists() has caused more real bugs than some of the “weirder” PHP features in this list 😄 Especially when consuming APIs where null and “field not present” have completely different meanings.

I’d also put in_array() on this list. Using it without strict mode can bring the same type-juggling surprises as ==:

in_array($value, $values, true)

That third argument is a tiny detail worth getting into the habit of using.__