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…
1. == and === Are Not the Same: PHP has two comparison operators: == and ===. The first compares values, while the second compares both value and type. For example, 5 == 5 outputs true, but 5 === 5 outputs false because 5 is an integer and 5 is a string. It is recommended to use === and !== for more predictable code.
2. The Weirdness of 0, 0, and False: PHP treats several values as false in certain situations. For instance, 0, 0, false, null, [], and an empty string can behave like false. This can cause issues when checking for the existence of a value. To be more specific, use if ($id === null) instead of if (!$id) to check for a missing ID.
3. The Null Coalescing Operator ??: This operator is useful for providing a default value if a variable is null. For example, $username = $_GET['username'] ?? 'Guest'; This will return 'Guest' if the 'username' key doesn't exist. It can also be chained for multiple default values.
4. ?? Is Different From ?: While both operators can appear similar, they have different purposes. Null coalescing ?? checks if a value exists and is not null, while ternary ?: checks if a value is truthy. For instance, $name = $user['name'] ?? 'Guest' will return 'Guest' if the 'name' key doesn't exist or is null. Using ?: instead can lead to unexpected results when checking for specific values like 0 or false.
5. Swapping Variables Without a Temporary Variable: In PHP, you can swap variables without using a temporary variable by using array destructuring. For example, $a = 10; $b = 20; [ $a, $b ] = [ $b, $a ]; This will result in $a = 20 and $b = 10, making the code cleaner and more concise.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.