php - shorthand if explanation ? mark operator -


for template engine use shorthand if condition. need check if value != null print out line if true. tried:

echo "test" ($user->affiliate_id !=null) ?    

i have no idea write behind ?.

the line $somevariable = $condition ? $valuea : $valueb equivalent to:

if ( $condition ) {     $somevariable = $valuea; } else {     $somevariable = $valueb; } 

so, basically, if condition true, $somevariable take first value after ? symbol. if false, take second value (the 1 after : symbol).

there's special case can not define first value , this: $somevariable = $somevalue ?: $someothervalue. it's equivalent to:

if ( $somevalue ) {     $somevariable = $somevalue; } else {     $somevariable = $someothervalue; } 

so, if $somevalue evaluates true (any value different 0 evaluated true), $somevariable catch value. otherwise, catch $someothervalue.

to give example:

function printgender( $gender ) {     echo "the user's gender is: " . ( $gender == 0 ? "male" : "female" ); }  printgender(0); // print "the user's gender is: male" printgender(1); // print "the user's gender is: female" 

another example:

function printvaluesstrictlydifferentthanzero( $value ) {     echo "value: " . ( $value ?: 1 ); }  printvaluesstrictlydifferentthanzero(0); // $value evaluates false, echoes 1 printvaluesstrictlydifferentthanzero(1); // $value evaluates true, echoes $value 

edit:

the operator ?: not called ternary operator. there multiple ways define ternary operator (an operator takes 3 operands). is a ternary operator, not the ternary operator. people call ternary operator because they're used and, probably, it's ternary operator vastly known in php, ternary operator way more general that.

it's name conditional operator or, more strictly, ternary conditional operator.

let's suppose define new operator called log base evaluates, inline, if logarithm of number $a base $c equals $b, syntax $correct = $a log $b base $c , returns true if logarithm right, or false if it's not.

of course operation hypothetical, is ternary operator, ?:. i'm gonna call logarithm checker operator.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -