Jump to content

where can i learn about using ? : in my true or false code


ricky spires

Recommended Posts

i keep seeing people use this kind of code but i cant find any document or help web pages on it. im sure there is but i done know what to call it.

 

i would really like to learn more about it

 

for example

$lang  = isset($_GET['lang']) ? (int)$_GET['lang'] : 1;

 

or

return !empty($result_array) ? array_shift($result_array) : false;

 

 

 

thanks

 

this is a perfect example :)

 

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

?>

In most cases, I assign the value to a variable anyhow, then use the variable in the string. More readable (to me, anyhow) that way.

 

echo "<select name=\"box\">\n";
foreach( $array as $k => $v ) {
     $selected = $k == $_POST['box'] ? 'selected="selected"' : '';
     echo "<option value=\"$k\" $selected>$v</option>\n";
}
echo "</select>\n"

;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.