I am looking to expand on my PHP knowledge, and I came across something I am not sure what it is or how to even search for it. I am looking at php.net isset code, and I see isset($_GET['something']) ? $_GET['something'] : ''
I understand normal isset operations, such as if(isset($_GET['something']){ If something is exists, then it is set and we will do something }
but I don't understand the ?, repeating the get again, the : or the ''. Can someone help break this down for me or at least point me in the right direction?
It's commonly referred to as 'shorthand' or the Ternary Operator.
$test = isset($_GET['something']) ? $_GET['something'] : '';
means
if(isset($_GET['something'])) { $test = $_GET['something']; } else { $test = ''; }
To break it down:
$test = ... // assign variable isset(...) // test ? ... // if test is true, do ... (equivalent to if) : ... // otherwise... (equivalent to else)
Or...
// test --v if(isset(...)) { // if test is true, do ... (equivalent to ?) $test = // assign variable } else { // otherwise... (equivalent to :)
In PHP 7 you can write it even shorter:
$age = $_GET['age'] ?? 27;
This means that the $age
variable will be set to the age
parameter if it is provided in the URL, or it will default to 27.
See all new features of PHP 7.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With