This is a very simple task but someone who is not comfortable with Php maybe can’t fulfill it. As the php manual states “The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C:”. With if we can compare numbers, alphanumeric variables what ever we desire. Below we can find several common situations.

Lets say that we want to compare a number only with another number:

<?php

$a = 10;

$b = 1;

if ($a $b){ echo “a is bigger than b”; }

elseif ($a < $b){ echo “b is bigger than a”; }

elseif ($a <= $b){ echo “b is bigger or equal to a”; }

..

else ($a == $b){ echo “b is equal to a”; }

?>

Please observe that at the third line we dont use only = but douple equal sign == . Thats classic for compare statements.   We have to remember also the structure of the if statement, first we use if, second we use elseif for as many statements that we like, at the end we use only else. We can use of course only if and else or only if. Also take in mind that we could use >= in any statement, it depends from what we want to compare.

Now lets say that we want to compare alphanumeric variables:

<?php

$a = “Hi there Number1!”;

$b = “–Second statement that we want to compare–”;

trim($a) ; trim($b) ;

if ($a == $b){ echo “a and b strings are the same”; }

elseif (!($a == $b)){ echo a and b strings are not the same; }

..

else (!($a)){ echo “There is no string to compare”; }

?>

You can very easy observe that we cant use > or < because it doesnt have any real point with words all are similar. trim() command is optional, we use it just to be sure that we dont get to compare empty lines and brakes at each side of the string, it removes the above. At the first like we are asking from php to check if $a and $b are the same, at the second if they are not the same (thats what ! does) and at the end if there is no string attached to $a variable we are telling to the script to print “There is no string to compare”. Of course we could end the script there or something similar.

Thank you for your time hope that helps someone!


Share This