How to Compare Numeric Variables with PHP

Josh Sherman
2 min read
Software Development 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.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles