PHP Tutorial [Part 1]

Back to Main

If Statements

This is where the fun begins. The If statements are pretty self-explanatory:
If something happens or some value exists then do something else do something else

<?php
$number=1;
if($number==1){
   echo "The number is 1!";
}else{
   echo "The number isn't 1! The number = ".$number;
}
?>

Output:

The number is 1!

If we change $number to 2, our output would be:

The number isn't 1! The number = 2

The if-statement has multiple parts. It always starts with “if” then a condition enclosed by parenthesis. In this case if($number==1). “==” is not a typo, it is called an operator.

Operators
== Equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
!= Does not equal
=== Exactly equal to (variable type and value)
!== Not exactly equal to (variable type and value)
&& And
|| Or

You can use any of these in your if conditions. The last 2 operators enable you to have multiple conditions for 1 if statement. ex: if($number!=1 && $number!=3)

Now, after your condition, you want to run some script. That portion needs to be in brackets {} if it is greater than 1 command. The backets show where the “then do something” starts and stops.

You don’t need an else or else if statement, but you can use those as well. Else means that the script will do something else if the condition isn’t met. Else if allows you to specify another condition. Lets try to put it all together in 1 script:

<?php
$var1=1;
$var2=2;
$var3=3;
if( ($var1+$var2) < 3 )
   echo $var1."+".$var2." is less than 3";
else if( ($var1+$var2)==3)
   echo $var1."+".$var2." is equal to 3";
else{
   echo $var1."+".$var2." is greater than 3!<br>";
   echo $var1."+".$var2."=".$var3;
}
?>

Output:

1+2 is equal to 3

This sums up everything we have talked about up to this point.

Next up – For Loops

Pages: 1 2 3 4 5 6