Skip to content

PHP IF statement for Boolean values: $var === true vs $var

In PHP, a variable can be evaluated as a Boolean value in an if statement without the need to explicitly compare it to true or false. For example, the following two if statements are equivalent:

Example of PHP IF statement

php
<?php

// Define a variable
$var = true;

// Check if the variable is equal to true using the strict equality operator (===)
if ($var === true) {
  // If the condition is met, the code inside the if statement will be executed
  echo "The variable is equal to true";
} else {
  // If the condition is not met, the code inside the else statement will be executed
  echo "The variable is not equal to true";
}

?>

<div class="alert alert-info flex not-prose"> Watch a course Learn object oriented PHP</div>

Example of checking if the variable is truthy in PHP IF statement

php
<?php

// Define a variable
$var = true;

// Check if the variable is truthy
if ($var) {
  // If the condition is true, execute the code inside the if block
  echo "The condition is true.";
}

?>

In the second example, PHP will automatically evaluate the variable as a Boolean value, so there's no need to use the comparison operator (===) to check if it is equal to true.

Additionally, you can use the negation operator (!) to check for false values

Example of using the negation operator (!) to check for false values in PHP

php
<?php

// Define the value of $var
$var = false;

// Check if $var is false
if (!$var) {
  // If $var is false, output a message
  echo "The value of \$var is false.";
}

?>

This will check if the variable is false.

Dual-run preview — compare with live Symfony routes.