Page 1 of 1

Not understanding a lin of a script.

Posted: Sun Jan 09, 2011 3:03 pm
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'] : "";

Re: Not understanding a lin of a script.

Posted: Sun Jan 09, 2011 4:02 pm
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 = "";
}

Re: Not understanding a lin of a script.

Posted: Sun Jan 09, 2011 4:28 pm
by califdon
It is called the ternary operator ("ternary" refers to 3 things). Read http://www.totallyphp.co.uk/tutorials/u ... rators.htm.

Re: Not understanding a lin of a script.

Posted: Mon Jan 10, 2011 2:43 pm
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;

Re: Not understanding a lin of a script.

Posted: Mon Jan 10, 2011 3:33 pm
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.