Can someone explain two snippets of code?
Posted by: Grand (---.static.vega-ua.net)
Date: June 14, 2010 07:26PM

Hi all.
$testbox = isset($_POST['testbox'])?$_POST['testbox']:null;
I was looking for answer at php tutorial, but unsuccessful.
I need to know what the "?" and the ":" are and how they work.
Greatly appreciated.

Options: ReplyQuote
Re: Can someone explain two snippets of code?
Posted by: c2dan (---.15-1.cable.virginmedia.com)
Date: June 14, 2010 07:50PM

?: is called a ternary operator. Its basically an inline if/else statement.

$testbox = isset($_POST['testbox'])?$_POST['testbox']:null;
The above the is the same as
if(isset($_POST['textbox'])) {
    $textarea = $_POST['textbox'];
} else {
    $textarea = null;
}

For more info head over to the manual here -> [php.net]
Scroll down to the ternary operator bit.

Options: ReplyQuote
Re: Can someone explain two snippets of code?
Posted by: audg (---.ccc.edu)
Date: June 14, 2010 07:51PM

This is like an "if then" statement in shorthand.

If $_POST['testbox'] exists, then $testbox = that variable. Otherwise $testbox is null.

Options: ReplyQuote
Re: Can someone explain two snippets of code?
Posted by: stevenmartin99 (---.b-ras2.blp.dublin.eircom.net)
Date: June 14, 2010 07:51PM

This is PHP'S ternary operator.

sample code would be
if ($x==$y)
                     {  $result = 'true';} 
    else 
                    {   $result = 'false';}


which you could write shorter using a ternary operator.
$result = ($x==$y)  ? 'true' :  'false';

Steven Martin
stevenmartin99@gmail.com
stevenmartin99@hotmail.com
PampServer.com - [pampserver.com]

Options: ReplyQuote


Sorry, only registered users may post in this forum.