Introduction:
The if statement is necessary for most programming, so it is important in PHP. Imagine that on January 1st you want to print out "Happy New Year!" at the top of your personal web page. With the use of PHP if statements you could have this process automated, months in advance, occuring every year on January 1st.
This idea of planning for future events is something you would never have had the opportunity of doing if you had just stuck with HTML.
The "Happy New Year" example would be a little difficult for you to do right now, so instead let's start off with the basics of the if statement. The PHP if statement tests to see if a value is true, and if it is, a segment of code will be executed.
The If Statement Is Like This:
PHP Code:
<?php
If (statement==something) { // The "{" is the same as saying "Then"
// Code to be executed if true
} // Same As Saying "End Statement"
?>
So what we're going to do, is make an if statement to check if someone's name is as it should be.
So first of all you're going to want to open your php tags as so:
PHP Code:
<?php
?>
Then you're going to add in a variable:
PHP Code:
<?php
$name = "Jimmy"; // The "$name" is the variable and "Jimmy" is what the variable equals to.
?>
Now we're going to make the statement check if the variable is true.
PHP Code:
<?php
$name = "Jimmy";
If ($name=="Jimmy") {
echo "Yes, your name is Jimmy!"; // echo makes the page displays what's in quotations.
}
?>
There we go! You've created an If Statement!
We can also go further and make it check if it you're not called Jimmy, and then if it's not, echo out something:
PHP Code:
<?php
/*
If Statement Tutorial By BreShiE
Enjoy This Snippit
If You Need Any Help Just Ask
*/
$name = "Jimmy";
If ($name=="Jimmy") {
echo "Yes, your name is Jimmy!";
} else {
echo "Your name is not Jimmy!";
}
?>
IF NOT:
Along with the If statement, you can tell the page "If NOT Then Do This".
EXAMPLE:
PHP Code:
<?php
$name = "Jimmy";
If (!($name=="Jimmy")) {
echo "Your name is not Jimmy!";
} else {
echo "Yes, your name is Jimmy!";
}
?>
Next up is the "AND" and "OR" statement, you can do this by placing the actual words or by using "&&" for "AND" and "||" for "OR".
OR EXAMPLE:
PHP Code:
$name = "Jimmy";
$name2 = "Bob";
If ($name=="Jimmy" || $name2=="Bob") {
echo "Yes, your name is Jimmy or Bob!!";
} else {
echo "Your name is not Jimmy or Bob!";}
?>
AND EXAMPLE:
PHP Code:
$name = "Jimmy";
$name2 = "Bob";
If ($name=="Jimmy" && $name2=="Bob") {
echo "Yes, your name is Jimmy and Bob!";
} else {
echo "Your name is not Jimmy and Bob!";}
?>