๐ŸŽ“ A1Learner
๐Ÿ”

PHP Comparisons

A comparison checks how two values relate and gives a true or false answer. A loose comparison converts values first, and a strict comparison also checks the type.

Tests on numbers

var_dump prints each answer with its type. Every answer here is a bool.

<?php
var_dump(5 > 3);
var_dump(5 == 5);
var_dump(5 != 5);

Loose and strict on the same values

The string "1" and the number 1 meet in two tests. The loose test converts the string first, and the strict test checks the type as well.

<?php
var_dump("1" == 1);
var_dump("1" === 1);

An int against a float

The values 1 and 1.0 look equal. Their types differ, so the strict test answers false.

<?php
var_dump(1 === 1.0);

A number against a letter string

The string "a" holds no number at all. PHP 8 treats this test as a text comparison.

<?php
var_dump(0 == "a");

Example

<?php
$mark = "60";
var_dump($mark == 60);
var_dump($mark === 60);

Key points

  • Each comparison ends with one bool answer.
  • The > operator tests whether the left value is greater than the right value.
  • The >= operator tests whether the left value is greater than or equal to the right value.
  • The <= operator tests whether the left value is less than or equal to the right value.
  • The == operator compares values after converting them.
  • The === operator also demands that both values share the same type.
  • The != operator tests whether values differ after converting, and !== is its strict form.

In this example, the mark is stored as the string "60". The loose test converts it and finds it equal to the pass mark 60. The strict test also checks the type. A string is not an int, so the strict test answers false.

Note

Older PHP versions answered true for 0 == "a", while PHP 8 compares the number as text and answers false.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz PHP Compiler

Exercise

What does var_dump("2" === 2) print?