How it will print hello - If hello is true, then the function must print hello, but if the function doesn’t receive hello or hello is false the function must print bye.
<?php
function showMessage($hello=false){
echo ($hello)?'hello':'bye';
}
?>
How it will print hello - If hello is true, then the function must print hello, but if the function doesn’t receive hello or hello is false the function must print bye.
<?php
function showMessage($hello=false){
echo ($hello)?'hello':'bye';
}
?>
So if you don't want any condition you can add default value bye
to para,eter. And simply echo it
<?php
function showMessage($hello="bye"){
echo $hello;
}
?>
Basically ($hello)?'hello':'bye';
is the shorthand for:
if ($hello == true) {
echo 'hello';
} else {
echo 'bye';
}
Reference: http://php.net/manual/en/control-structures.if.php
You are using ternary operator inside function, which will check the type of variable true
or false
. By default $hello
variable type will be false.
So below code will be check if variable type is true then prine 'hello' else ternary operator will be print 'bye'.
It is same as like below
if($hello==true){
echo 'hello';
}else{
echo 'bye';
}
The reason why showMessage('abc')
now prints 'hello' is because the ($hello) will evaluate to true as a non-empty string.
I guess what you are looking for is the type comparison operator ===
. It will check whether the argument passed is actually a boolean value.
function showMessage($hello=false) {
echo ($hello === true)?'hello':'bye';
}