PHP Syntax Question: What Does the Question Mark and Colon Mean

PHP syntax question: What does the question mark and colon mean?

This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.

Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.

$param = isset($_GET['param']) ? $_GET['param'] : 'default';

There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:

$result = $x ?: 'default';

It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset or a null coalescing operator which is introduced in PHP7:

$param = $_GET['param'] ?? 'default';

php - Meaning of question mark colon operator

It is a shorthand for an if statement.

$username = $_COOKIE['user'] ?: getusername($_COOKIE['user']);

Is the same as

if( $_COOKIE['user'] ) 
{
$username = $_COOKIE['user'];
}
else
{
$username = getusername($_COOKIE['user']);
}

see test suite here: https://3v4l.org/6XMc4

But in this example, the function 'getusername' probably doesn't work correct, because it hits the else only when $_COOKIE['user'] is empty. So, the parameter inside getusername() is also kind of empty.

What does the question mark as well as the colon (:) do in php, particularly in this line?

This is called a ternary operator. It is presented in this form :

condition ? value_if_condition_true : value_if_condition_false;

For example you can use the result of this expression for an assignment, let's say :

$load_page = is_user_logged_in() ? true : false;

In fact, this is the equivalent of writing :

 if (is_user_logged_in())
$load_page = true;
else
$load_page = false;

EDIT Because I love the ternary operator, I want to write more.
This operator form has no effect on performance or behaviour compared to the classic else/if format, and only serves the purpose of being an elegant one liner. (Which is the reason why some languages don't implement it, taking the view that it is unnecessary and often bad practice to have N ways of writing the same instruction)

But to show how elegant it is, imagine you know the age of a user, and the age_of_subscription to your website, and you want to display a message depending on these two variables according to these rules :

  • if the user is older than 20 and had a subscription for more than 3 year, he is allowed to a discount
  • if the user is younger than 20 and had a subscription for more than 1 years, he is allowed to a discount
  • in any other case, the user is paying the full price.

In the classic IF/ELSE form, you would write :

if ($age > 20)
{
$text = "You are above 20 and you have been a user for ";
if ($age_of_subscription > 3)
{
$text .= "more than 3 years so you are allowed a discount";
}
else
{
$text .= "less than 3 years so you are paying full price";
}

}
else
{
$text = "You are below or 20 and you have been a user for ";
if ($age_of_subscription > 1)
{
$text .= "more than 1 year so you are allowed a discount";
}
else
{
$text .= "less than 1 year so you are paying full price";
}

}
echo $text;

But now, watch the beauty of ternary operator :

echo 'You are ',
($age > 20 ?
($age_of_subscription > 3 ? 'above 20 and you have been a user for more than 3 years
\ so you are allowed a discount' : 'above 20 and you have been a user for less than 3 years
\ so you are paying full price.')
: ($age_of_subscription > 1 ? 'below or 20 and you have been a user for more than 1 year
\ so you are allowed a discount' : 'below or 20 and you have been a user for less than 1 year
\ so you are paying full price.')); // pretty uh?

PHP question mark

This is called the Ternary Operator, and it's common to several languages, including PHP, Javascript, Python, Ruby...

$x = $condition ? $trueVal : $falseVal;

// same as:

if ($condition) {
$x = $trueVal;
} else {
$x = $falseVal;
}

One very important point to note, when using a ternary in PHP is this:

Note: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.
source

What does double question mark (??) operator mean in PHP

It's the "null coalescing operator", added in php 7.0. The definition of how it works is:

It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

So it's actually just isset() in a handy operator.

Those two are equivalent1:

$foo = $bar ?? 'something';
$foo = isset($bar) ? $bar : 'something';

Documentation: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce

In the list of new PHP7 features: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

And original RFC https://wiki.php.net/rfc/isset_ternary


EDIT: As this answer gets a lot of views, little clarification:

1There is a difference: In case of ??, the first expression is evaluated only once, as opposed to ? :, where the expression is first evaluated in the condition section, then the second time in the "answer" section.

Method followed by colon and a question mark and a class

This syntax means that the method is forced to return NULL (what the question mark stands for) or and instance of the declared class. Refer to: php docs.

If something else is returned, this will cause an error like: Return value of Name\Space::method() must be of the type ..., ... returned in /Path/To/File.php on line ....

It's good practice to use this strict typing in object oriented programming so the code is more unambiguous and less sensitive to errors.

But it's not obligated to use, your code will work perfectly fine if you remove the return type and just use public function getParentProject().

What does the question mark and the colon (?: ternary operator) mean in objective-c?

This is the C ternary operator (Objective-C is a superset of C):

label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;

is semantically equivalent to

if(inPseudoEditMode) {
label.frame = kLabelIndentedRect;
} else {
label.frame = kLabelRect;
}

The ternary with no first element (e.g. variable ?: anotherVariable) means the same as (valOrVar != 0) ? valOrVar : anotherValOrVar

Question mark and colon in JavaScript

It is called the Conditional Operator (which is a ternary operator).

It has the form of: condition ? value-if-true : value-if-false
Think of the ? as "then" and : as "else".

Your code is equivalent to

if (max != 0)
hsb.s = 255 * delta / max;
else
hsb.s = 0;

What does this PHP syntax mean? (question marks)

It's a ternary operator.

It's simply short-hand for:

if (isset($_SESSION['id']))
return true;
else
return false;

What is a Question Mark ? and Colon : Operator Used for?

This is the ternary conditional operator, which can be used anywhere, not just the print statement. It's sometimes just called "the ternary operator", but it's not the only ternary operator, just the most common one.

Here's a good example from Wikipedia demonstrating how it works:

A traditional if-else construct in C, Java and JavaScript is written:

if (a > b) {
result = x;
} else {
result = y;
}

This can be rewritten as the following statement:

result = a > b ? x : y;

Basically it takes the form:

boolean statement ? true result : false result;

So if the boolean statement is true, you get the first part, and if it's false you get the second one.

Try these if that still doesn't make sense:

System.out.println(true ? "true!" : "false.");
System.out.println(false ? "true!" : "false.");


Related Topics



Leave a reply



Submit