2

So I'm using the following php code to set variables that are received from a POST method, but I'm interested in how it works.

$var1 = isset($_REQUEST['var1']) ? $_REQUEST['var1'] : 'default';

I understand what it does, but I don't understand the syntax.

Thanks for the help :)

noob
  • 8,053
  • 4
  • 34
  • 64
  • 1
    `$_REQUEST('var1')` should be `$_REQUEST['var1']`, shouldn't it? – deceze Apr 03 '12 at 09:09
  • 1
    possible duplicate of [What is ?: in PHP 5.3?](http://stackoverflow.com/questions/2153180/what-is-in-php-5-3) and [many others](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php). Please use the PHP tag wiki before asking questions about symbols in PHP. – Quentin Apr 03 '12 at 09:09
  • 1
    Actually what you are typing is not setting a variable from $_POST, but from a requested variable on the site. $_REQUEST is just checking if the variable is from $_GET or $_POST as mentioned above. But what you do is wrong, because if there is a $_GET variable set with the same name, it will get you the $_GET variable instead. Use pure $_POST for that. – Panagiotis Apr 03 '12 at 09:10
  • @deceze and Panagiotis yes you're both right because $_REQUEST is an associative **array** that by default contains the contents of $_GET, $_POST and $_COOKIE. – noob Apr 03 '12 at 09:13

6 Answers6

5

? is just a short and optimised notation of doing this:

if (isset($_REQUEST["var1"])) // If the element "var1" exists in the $_REQUEST array
   $var1 = $_REQUEST["var1"]; // take the value of it
else
   $var1 = "default"; // if it doesn't exist, use a default value

Note that you might want to use the $_POST array instead of the $_REQUEST array.

huysentruitw
  • 25,048
  • 8
  • 76
  • 120
3

This is a short hand IF statement and from that you are assigning a value to $var1

The syntax is :

$var = (CONDITION) ? (VALUE IF TRUE) : (VALUE IF FALSE);
cloakedninjas
  • 3,346
  • 1
  • 27
  • 41
3

You probably mean ternary operator

Syntax it's same like

if(isset($_REQUEST('var1') ) {
    $var1 = ? $_REQUEST('var1')
}else {
    $var1 =: 'default';
}
rkosegi
  • 12,129
  • 5
  • 46
  • 75
2

It's the synatx of the ternary operator. It's shorthand for if/else. Please read PHP Manaul

Sebastian Schmidt
  • 1,088
  • 7
  • 17
0

This is a 'ternary operator', what it says is:-

If var1 is set as a post variable then set var1 to that value, otherwise setvar1 to be the string 'default'. Using traditional syntax it would be:-

if (isset($_REQUEST('var1')) { $var1 = $_REQUEST('var1'); } else { $var1 = 'default'; }
Purpletoucan
  • 5,992
  • 2
  • 19
  • 28
-1

its a short way of doing an if. if you are expecting a post variable its must better to use _POST rather than request.

the "?" says if the isset($_REQUEST) is true, then do the everything between the ? and : otherwise do everything between the : and the ;

encodes
  • 741
  • 4
  • 18