How to Compare Numeric Variables with PHP

Comparing numeric values is a very common programming task. Which number is greater? is lesser? equal? In PHP like any C-style language, you can do these comparisons with a simple if ( ... ) { ... } statement:

if ($var1 > $var2)
{
	echo $var1 . ' is greater than ' . $var2
}
elseif ($var1 < $var2)
{
	echo $var1 . ' is less than ' . $var2
}
elseif ($var1 == $var2)
{
	echo $var1 . ' is equal to ' . $var2
}

You could use an else { ... } in there given the complexity of the checks but for the sake of example I’ve spelled out each case. Based on the output you should be able to understand the logic, just basic relational operators like we learned in grade school. It’s worth noting the use of the double equals sign with means “is equivalent to”, whereas a single equals sign is for assignment of a variable and triple equals would identify an exact match.

Here are some additional relational operators that you could potentially need when comparing numbers:

if ($var1 >= $var2)
{
	echo $var1 . ' is greater than or equal to ' . $var2
}

if ($var1 <= $var2)
{
	echo $var1 . ' is less than or equal to ' . $var2
}

if ($var1 != $var2)
{
	echo $var1 . ' does not equal ' . $var2
}

Not much to it, now you can compare numeric variables to each other! Remember, these relationship operators can be applied to all types of variables (even strings) so be mindful when you are comparing variables that you are comparing variables of like type.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.