What does this PHP (function / construct?) Do, and where can I find additional documentation?

Simple question. Here is the code.

$r = rand(0,1); $c = ($r==0)? rand(65,90) : rand(97,122); $inputpass .= chr($c); 

I understand what it does as a result of end , but I would like to get a more detailed explanation of how it works, so I can use it myself. Sorry if this is a bad question.

If you don't know what I'm asking for, its function (function?) Used here:

$c = ($r==0)? rand(65,90) : rand(97,122);

+2
source share
4 answers

This is called a ternary operator. It is actually equivalent

 if ($r == 0) { $c = rand(65, 90); } else { $c = rand(97, 122); } 

But this is obviously a little more compact. Read the docs for more details.

+7
source

It just means:

 if($r==0){ $c = rand(65,90); else{ $c = rand(97,122); } 

If the statement is true, the first operation after that ? is executed, otherwise the operation is performed after :

It is called the ternary operator .

+1
source

His ternary operator

 <?php // Example usage for: Ternary Operator $action = (empty($_POST['action'])) ? 'default' : $_POST['action']; // The above is identical to this if/else statement if (empty($_POST['action'])) { $action = 'default'; } else { $action = $_POST['action']; } ?> 

Expression (expr1)? (expr2): (expr3) evaluates to expr2 if expr1 is TRUE and expr3 if expr1 evaluates to FALSE. Starting with PHP 5.3, you can exclude the middle part of the ternary operator. Expression expr1 ?: Expr3 returns expr1 if expr1 is TRUE and expr3 otherwise.

0
source

It is called a ternary operator. This is similar to the if / else construct, but the difference is that an expression using the ternary operator gives a value.

That is, you cannot set a variable to the result of the if / else construct:

 // this doesn't work: $c = if ($r == 0) { rand(65, 90); } else { rand(97, 122); } 

You can read more about this here: http://php.net/ternary#language.operators.comparison.ternary

The triple operator is often misused. There is little benefit in using the example you showed. Some programmers like to use compact syntactic sugar , even if it is not needed. Or even when it is more clear to write the complete if / else construct.

A ternary operator can also hide test coverage if you use a tool that measures lines of code covered by tests.

0
source

Source: https://habr.com/ru/post/1313655/


All Articles