The ternary operator and If/Else

The ternary operator ":?" to make If/Else structures smaller and compact is a beautiful thing. Evaluate the following example and how it could be written in a much more compact and faster way. You can use this technique in several languages. I have personally used it during PHP, C and JavaScript development quite often.

Example with "if/else"
$true_or_false = true;
$need_a_value = '';

if($true_or_false == true) {
  $need_a_value = 'It was true.';
} else {
  $need_a_value = 'It was not true.';
} 


Example with the ternary operator "?:"
$true_or_false = true;
$need_a_value = '';

$need_a_value = ($true_or_false==true?'It was true.':'It was not true.'); 


Written by: Dag Jonny Nedrelid
©2007-2012 http://thronic.com


Feel free to leave a comment.
Name:
URL:
0