# Weak comparisons

#### **Backward Incompatible Changes**

View [https://www.php.net/manual/en/migration80.incompatible.php](https://www.php.net/manual/en/migration80.incompatible.php)

#### **Key principles**

Follow these fundamental rules when writing compatible code:

<p class="callout success">**Analyze variable types:** Always understand what types and values a variable can hold.</p>

<p class="callout success">**Use strict comparisons:** Prefer `===` and `!==` over `==` and `!=` to avoid implicit type coercion.</p>

<p class="callout success">**Declare types explicitly:** Always use type declarations for function/method parameters and return types.</p>

<p class="callout success">**Validate with strict checks:** Use strict type checks in conditional statements to prevent unexpected behavior (e.g., `in_array` with `true` as third parameter).  
Example: [https://www.php.net/manual/en/function.in-array.php#example-2](https://www.php.net/manual/en/function.in-array.php#example-2)</p>

<p class="callout success">**Use PHP constants:** Always use predefined PHP constants instead of numbers (e.g., `UPLOAD_ERR_OK` instead of `0`).</p>

<p class="callout success">**Enable strict types:** Add `declare(strict_types=1);` at the top of your PHP files ***when possible***.</p>

#### **Strings**

Use `empty()` instead of comparing with empty string.

<table id="bkmrk-%E2%9D%8C-don%27t-%E2%9C%85-do-if-%28%24a-"><tbody><tr><th>❌ DON'T</th><th>✅ DO</th></tr><tr><td>```php
if ($a == '') {
    // ...
}
```

</td><td>```php
if (empty($a)) {
    // ...
}
```

</td></tr><tr><td>```php
if ($a != '') {
    // ...
}
```

</td><td>```php
if (!empty($a)) {
    // ...
}
```

</td></tr></tbody></table>

#### **Checkbox values**

In PHP 8, comparing numeric strings with numbers produces different results.

<table id="bkmrk-%E2%9D%8C-don%27t-%E2%9C%85-do-if-%28%24a--1"><tbody><tr><th>❌ DON'T</th><th>✅ DO</th></tr><tr><td>```php
if ($a == 0) {
    // ...
} elseif ($a == 1) {
    // ...
} else {
    // ...
}
```

</td><td>```php
if (strval($a) === '0') {
    // ...
} elseif (strval($a) === '1') {
    // ...
} else {
    // ...
}
```

</td></tr></tbody></table>