user2678132
user2678132

Reputation: 115

understanding the ternary operator in php

I was hoping someone could explain to me what the ? -1 : 1; mean in the below ternary operator? Many thanks

<?php
 $people = array(
 array( "name" => "hank", "age" => 39 ),
 array( "name" => "Sarah", "age" => 36 ),
 );
 usort( $people, function( $personA, $personB ) {
 return ( $personA["age"] < $personB["age"] ) ? -1 : 1;
 } );

 print_r( $people );

Upvotes: 2

Views: 824

Answers (3)

Chetan Ameta
Chetan Ameta

Reputation: 7896

Ternary operator logic is the process of using (condition) ? (true return value) : (false return value) statements to shorten your if/else structures.

So in your case if/else will be like below code:

if($personA["age"] < $personB["age"]) {
   return  -1 ;
}
else{ 
   return 1;
}

for more detail have alook at: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary

In the case of usort function it will return -1 to indicate that the value in $personA['age'] is less than the one in $personB['age']. for more detail have a look at how does usort work? and http://php.net/manual/en/function.usort.php

Update 1

The callback in usort provided to the sorting functions in PHP have three return values:

0:  both elements are the same
-1 (<0): the first element is smaller than the second
1 (>0):  the first element is greater

Now, usort probably uses some kind of quicksort or mergesort internally. For each comparison it calls your callback with two elements and then decides if it needs to swap them or not.

Upvotes: 1

It's just shorthand IF, ELSE essentially, can be really handy

$name = "Jack";

if($name == "Jack")
    echo "You are Jack";
else 
    echo "You are not Jack";

VS

echo ($name == "Jack") ? "You are Jack" : "You are not Jack";

I belive in php you can call functions if the condition is/isn't met, so in this example if $ok is true, we run the pass function else fail function.

($ok) ? pass() : fail(); 

Upvotes: 1

Pupil
Pupil

Reputation: 23948

Ternary operator is a short hand for if else.

Ternary operator makes code shorter and cleaner.

Basic syntax for ternary operator is:

[assignment variable] = (condition) ? [if condition is true] : [if condition is false]

If if and else also has only one statement, then you can use ternary operator.

For example:

if (TRUE) {
 $a = 1;
}
else {
 $a = 0;
}

Can be simply written as:

$a = (TRUE) ? 1 : 0;

Upvotes: 1

Related Questions