PHP single line if statement, short if statement, condensed if statement
This is something I always have to google, so I figured I'd put it here for my own reference (and hopefully yours too).
The single line if statement is written as follows:
$canIaffordit = ($price <= 1.50) ? "yep" : "nope";
Where $canIaffordit is the variable that will be assigned the value "yep" if $price is less than or equal to $1.50, or the value "nope" if $price is greater than $1.50.
Remember, this can also be used for any PHP comparison operator. You could also use it to run functions that return values such as:
$packsoframenIcanafford = ($moneys > 0) ? packsoframen($moneys) : 0;
where the function packsoframen would return the number of packs of ramen I can afford given the amount of money I have. (So if I have $1.00, I can afford 10 packs of ramen, and the function will return 10)
The short if statement, one line if statement, or single line if statement, is called the ternary operator in PHP.
The single line if statement is written as follows:
$canIaffordit = ($price <= 1.50) ? "yep" : "nope";
Where $canIaffordit is the variable that will be assigned the value "yep" if $price is less than or equal to $1.50, or the value "nope" if $price is greater than $1.50.
Remember, this can also be used for any PHP comparison operator. You could also use it to run functions that return values such as:
$packsoframenIcanafford = ($moneys > 0) ? packsoframen($moneys) : 0;
where the function packsoframen would return the number of packs of ramen I can afford given the amount of money I have. (So if I have $1.00, I can afford 10 packs of ramen, and the function will return 10)
The short if statement, one line if statement, or single line if statement, is called the ternary operator in PHP.








0 Comments:
Post a Comment
Links to this post:
Create a Link
<< Home