PHP Tutorial: No IF’s, ELSEIF’s, or ELSE’s about it!

Once you’re comfortable with strings and variables, it’s time to really put them into action. You can accomplish this byusing PHP’s if/elseif/else structure, don’t worry I’ll explain. The if() structure evaluates an expression, that expression will return either TRUE or FALSE. Let’s do an example:

/* we'll set a variable, and use it in an if() statement */
$mynumber = 10;
/* now we build the if() {} else {} statement */
if ( $mynumber > 5 ) {
    echo 'The variable $mynumber is greater than 5!';
} else { /*otherwise, it must not be greater than 5 */
    echo 'The variable $mynumber is not greater than 5.';

So let’s talk about what just happened. We told PHP to check if the variable $mynumber was greater than. In our case, $mynumber was greater than so that example should display: The variable $mynumber is greater than 5! After that, if the expression ($mynumber > 5) returns false the else code block will come into play, and display: The variable $mynumber is not greater than 5.

“Mike you mentioned elseif, what’s that?” Well the elseif() goes between the if() {} and the else {}, like another level of expression checking. Let’s see a new example:

/* so first, we'll set a variable
this time we'll use a string */
$apple = 'red';
/* now we'll build our if/elseif/else structure 
We're going to use the == (equal to) operator */
if ( $apple == 'green' ) {
    echo 'The apple is green!';
} elseif ( $apple == 'yellow' ) {
    echo 'The apple is yellow!';
} else {
    echo "The apple is not green or yellow, but $apple.";

Note: When setting a variable or echoing a string, or ending any statement in PHP be sure to end your statement with a semi-colon ( ; ).

So to go over what just happened: We set a variable named $apple and set it to have a value of red. We then asked PHP to check if that variable had a value of green, and if not check if it has a value of yellow, and once again, if not, execute the code inside the else {} code block, which will echo out what color our $apple actually is.

Hopefully that helps you understand the structure behind an if/elseif/else structure.

Thanks for reading, I hope you found this helpful!

Author: Mike on March 23, 2011
Category: PHP, Tutorials
Tags: , ,

One thought on “PHP Tutorial: No IF’s, ELSEIF’s, or ELSE’s about it!”

  1. Lissa says:

    And I was just wondering about that too!

Comments are closed.

Last articles