Use of ? and : in PHP

Asked

Viewed 35,105 times

28

Can you explain to me what it’s for ? and : in PHP?

For example in this case:

public function url_format($post,$extra=FALSE) {    
    $title = isset($post->post_title) ? $post->post_title : $post->title;
    $title = isset($post->url) ? $post->url : $title;
    return $lang_domin.strtolower(url_title($title)).'-postid-'.$post->id.$extra;
}
  • Possible duplicates: http://answall.com/questions/9962/comorsimplificar-o-seguinte-if-em-php/ or http://answall.com/questions/3647/quando-usar-condi%C3%A7%C3%A3o-tern%C3%A1ria ...

4 answers

38


This is called conditional or ternary operator. It works like a if. It tests a condition (the first operand), if it is true, the result of the operation is the first value (after the ?, the second operand), if it is false, then the result is the second value (after the :, the third operand).

Note that he cannot execute commands, can only have expressions. It is not always recommended to use it since it can make it difficult to read. But most of the time where you have only a simple and short expression as a result, when you don’t nest one ternary operator with another, when it doesn’t require putting several parentheses to disambiguate what you’re doing, it gets shorter and very easy to understand. Some people are against it always but I find exaggeration. It is very useful in many cases. Saying you should never use it is as bad as saying you should always use it.

The conditional name comes precisely because he must test a condition to know what is the result of his operation (of his "account"). And he’s also called the ternary because he’s the only operator with three operands. The day you create another one - I doubt it will - will be confusing :)

There is an explanation with more details in other questions like that one and that one. The language may be different but the idea is the same.

  • 2

    Thank you for your reply, you made it very clear what you wanted to know ;)

  • @bigown will edit the answer with the performance test or will create another ? I rarely find code in php using this operator, I see it more in C++

  • There is some performance gain when using ternary operator instead of a conditional operator?

  • @Gabrielrodrigues rarely finds it because most PHP programmers do not know the language well or have prejudice with the resource. But I won’t edit the answer because the question doesn’t speak in performance. It would have to be another question to keep the focus.

  • @Eduardosilva I have the test ready but I don’t have it question asking this, if anyone posts, I reply :P

  • @bigown, I asked a question: http://answall.com/questions/56830/h%C3%A1-some-performance-gain-to-use-operator-tern%C3%A1rio-to-Inv%C3%A9s-to-an-op

Show 1 more comment

20

In your example, the same makes use of a conditional operator whose condition is separated from the results by the character ? and the results separated by the character :.

What is a conditional operator "?:"

A conditional operator, as its name implies, is an operator operating on the basis of a condition.

It is part of the group of ternary operators because it takes three operands: a condition, a result for true, and a result for false.

In its essence, it is a simple way to summarize checks making the code more compact:

if ("condição") {
  $bubu = "sim";
}
else {
  $bubu = "não";
}

Turns into:

$bubu = "condição" ? "sim" : "não";

In this operator, the condition evaluation always returns a boleanus triggering the use of the first value in case TRUE or second value in case FALSE.

This operator is also known by the following names::

  • IF conditional
  • Shorthand IF
  • Inline IF
  • Ternary Operator (ternary operator)

Perks

  • Makes logic programming simple if / else fastest
  • Reduces the amount of code
  • Makes code maintenance easier
  • Allows the use of logic inline avoiding breaking the code in multiple lines:

    echo "Bem vindo, ".($loginAtivo?$primeiroNome:"Convidado").".";
    

Disadvantages

Except for the excess of its use, the conditional operator has no disadvantages. Its own creation started from the principle of simplifying small logical actions.

An example of its disadvantageous use where code maintenance becomes a nightmare:

// Devolve os dias em determinado mês
$dias = ($mes == 2 ? ($ano % 4 ? 28 : ($ano % 100 ? 29 : ($ano %400 ? 28 : 29))) : (($mes - 1) % 7 % 2 ? 30 : 31));

The example above is an incorrect use of this operator because reading the code is difficult, becoming more complete than regular if~else.

Common mistakes

It is common to refer to this operator as operador ternário, despite being a conditional operator of the group of ternary operators, because in the PHP language, it is the only one that exists. (?)

Another conditional Operator is the "?:" (or Ternary) Operator.

That translated:

Another conditional operator is the "?:" (ternary) operator.

The very PHP documentation for this operator leads us to make use of the name operador ternário, that, as per reply by @Maniero:

The day you create another one - I doubt it will - will be confusing :)

PHP > 5.3

From PHP version 5.3, it is possible to further reduce the code, leaving out the middle part expr1 ?: expr3:

$bubu = "sim" ?: "não";

Will return the first expression if it evaluates to TRUE, otherwise returns the third expression.

The use in this form will no longer be so common, but to have been implemented, must come in handy at some point.

  • Has how to make a if elseif Else using conditional operator?

  • @Juliohenrique tem sim https://answall.com/a/523100/187610

17

Is a ternary operator, the expression (expr1) ? (expr2) : (expr3) is evaluated to expr2 if expr1 is assessed as TRUE, or expr3 if expr1 is assessed as FALSE.

It would be the same as:

public function url_format($post,$extra=FALSE) {
   if(isset($post->post_title)){
      $title = $post->post_title;
   } else {
      $title = $post->title;
   }
   ...
}
  • This does not answer the question, could improve?

  • 1

    I’m sorry @Guilhermenascimento more disagree, this answers the question exactly.

  • 1

    is responsive, but not how it works, just indicates a link, you could have copied something from the link to my view, but it’s just an opinion and suggestion for you to improve your answer, it’s up to you to accept or not, a legal excerpt to add would be: Does the expression (Expr1) ? (expr2) read: (expr3) is evaluated to expr2 if Expr1 is rated TRUE, or expr3 if Expr1 is rated FALSE.

  • Okay, @Guilhermenascimento thank you for the suggestion, as soon as I have a better time the answer.

  • I made an issue, feel free to do the rollback if you disagree, I won’t be upset :) +1 for your answer

  • 1

    @Guilhermenascimento In no way is its edition quite pertinent

Show 1 more comment

1

It is worth mentioning the conditional structure "If/Elseif/Else" in ternary

That is, if you want two or more expressions, without requiring the use of "If/Elseif/Else" or "Switch/Case" just follow the pattern condicao ? true : (condicao ? false : (condicao ? null) ...) according to the documentation Operators of Comparison php.

function entradas($a) {
    return $a == "true" ? "sim" : ($a == "false" ? "não" : ($a == "sopt" ? "stack overflow em portugues" : "n/a"));
}

echo entradas("sopt"); // stack overflow em portugues;

However, avoid "stacking" the ternary expressions, so as not to end up falling in the behavior non-obvious! test the code


See that you will have the same result as using the examples below:

  • If/Else
function entradas($a) {
    if ($a == "true") {
        return "sim";
    } elseif ($a == "false") {
        return "não";
    } elseif ($a == "sopt") {
        return "stack overflow em portugues";
    } else {
        return "n/a";
    }
}

echo entradas("true"); // sim
  • Switch/Case
function entradas($a) {
    switch ($a) {
        case "true":
            return "sim";
        case "false":
            return "não";
        case "sopt":
            return "stack overflow em portugues";
        default:
            return "n/a";
    }
}

echo entradas("false"); // não

Browser other questions tagged

You are not signed in. Login or sign up in order to post.