Rob
Rob

Reputation: 8101

What does this PHP (function/construct?) do, and where can I find more documentation on it?

Simple question. Here is this code.

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

I understand what it does in the end result, but I'd like a better explanation on how it works, so I can use it myself. Sorry if this is a bad question.

If you're unsure of what I'm asking about, its the (function?) used here:

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

Upvotes: 2

Views: 227

Answers (4)

Bill Karwin
Bill Karwin

Reputation: 562290

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

That is, you can't set a variable to the result of an if/else construct:

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

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

The ternary operator is frequently misused. There's little benefit to using it in the example you showed. Some programmers love to use compact syntactic sugar even when it's not needed. Or even when it's more clear to write out the full if/else construct.

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

Upvotes: 0

Russell Dias
Russell Dias

Reputation: 73292

Its the 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'];
}

?>

The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE. Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Upvotes: 0

Chris
Chris

Reputation: 10435

That's called a ternary operator. It's effectively the equivalent of

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

But it's obviously a bit more compact. Check out the docs for more info.

Upvotes: 7

Babiker
Babiker

Reputation: 18798

That simply 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, else the operation after : is executed.

Its called a ternary operator.

Upvotes: 1

Related Questions