Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

Tags:

php

isset

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?

like image 915
user1625186 Avatar asked Aug 25 '12 23:08

user1625186


2 Answers

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 :) 
like image 146
uınbɐɥs Avatar answered Sep 22 '22 06:09

uınbɐɥs


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.

like image 32
George Garchagudashvili Avatar answered Sep 18 '22 06:09

George Garchagudashvili