PHP - What's going on here?

Hi.. Quite new to LAMPy stuff - I'm trying to pick apart a bit of code here. Can someone explain what's going on? I get what it's doing, I just can't put a name to the functionality to explore it further if that makes sense. php > unset ($error); php > echo (empty($error)) ? 'The string is empty' : 'The string has something in'; The string is empty php > $error = "Something"; php > echo (empty($error)) ? 'The string is empty' : 'The string has something in'; The string has something in php > Obviously the ? and : is doing some decision making based on a true/false from the empty($error) - is this part of 'echo' or something else? Googling "PHP echo ? :" doesn't yield much of interest 🙂 cheers!
5 Replies
ErickO
ErickO•2y ago
Ternary operator and it is not party of echo, no, just a comparison operator that exists
Jochem
Jochem•2y ago
echo (empty($error)) ? 'The string is empty' : 'The string has something in';
echo (empty($error)) ? 'The string is empty' : 'The string has something in';
is a fancy way of writing
if (empty($error)) {
echo 'The string is empty';
} else {
echo 'The string has something in';
}
if (empty($error)) {
echo 'The string is empty';
} else {
echo 'The string has something in';
}
foggy
foggyOP•2y ago
Got it!! Thanks a lot! Makes sense... (condition) ? true : false ;
Jochem
Jochem•2y ago
echo prints out the result of whatever expression follows it
echo 1+2;
echo 1+2;
would print 3 to the screen. So what you're doing with
echo (empty($error)) ? 'The string is empty' : 'The string has something in';
echo (empty($error)) ? 'The string is empty' : 'The string has something in';
is telling PHP to echo the result of
empty($error) ? 'The string is empty' : 'The string has something in';
empty($error) ? 'The string is empty' : 'The string has something in';
which is the part before the : if the part before ? is true, and the part after if it's false
foggy
foggyOP•2y ago
yep makes total sense thanks both... !
Want results from more Discord servers?
Add your server