Not understanding a lin of a script.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Crux
Forum Newbie
Posts: 7
Joined: Sat Jan 08, 2011 7:01 am

Not understanding a lin of a script.

Post by Crux »

Code: Select all

$name = isset($_GET['name']) ? $_GET['name'] : "";
I am trying to understand some script but I have some problems understanding this line and some similar to it. I understand that information is collected from a form and that that is stored in the variable $name when it is set.

Code: Select all

$name = isset($_GET['name'])
However I have absolutely no clue what the following part does and the PHP website is not helping me out that much (guess I am searching it the wrong way or something.

Code: Select all

? $_GET['name'] : "";
d3ad1ysp0rk
Forum Donator
Posts: 1661
Joined: Mon Oct 20, 2003 8:31 pm
Location: Maine, USA

Re: Not understanding a lin of a script.

Post by d3ad1ysp0rk »

It's shorthand for an if/else statement.

Code: Select all

$name = isset($_GET['name']) ? $_GET['name'] : "";
is the same as

Code: Select all

if (isset($_GET['name'])){
  $name = $_GET['name'];
} else {
  $name = "";
}
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Not understanding a lin of a script.

Post by califdon »

It is called the ternary operator ("ternary" refers to 3 things). Read http://www.totallyphp.co.uk/tutorials/u ... rators.htm.
Crux
Forum Newbie
Posts: 7
Joined: Sat Jan 08, 2011 7:01 am

Re: Not understanding a lin of a script.

Post by Crux »

So the following would be a correct statement to give the variable number the value of 5 if no input has been given by a user in the field of a form?

Code: Select all

$number = isset($_POST['fnumber']) ? $number = 0;
d3ad1ysp0rk
Forum Donator
Posts: 1661
Joined: Mon Oct 20, 2003 8:31 pm
Location: Maine, USA

Re: Not understanding a lin of a script.

Post by d3ad1ysp0rk »

Crux wrote:So the following would be a correct statement to give the variable number the value of 5 if no input has been given by a user in the field of a form?

Code: Select all

$number = isset($_POST['fnumber']) ? $number = 0;
Incorrect, that code would result in a syntax error I believe, as it's missing the second value.

$variable = condition ? trueValue : falseValue;

Code: Select all

$number = isset($_POST['fnumber']) ? $_POST['fnumber'] : 5;
That would set $number to $_POST['fnumber'] if it was set, and 5 otherwise.
Post Reply