CodeIgniter Forums
If, then, else shorthand (aka ternary or conditional operator)? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: If, then, else shorthand (aka ternary or conditional operator)? (/showthread.php?tid=35157)



If, then, else shorthand (aka ternary or conditional operator)? - El Forum - 10-20-2010

[eluser]pbreit[/eluser]
Curious what the board thinks of using if/then/else shorthand (aka ternary or conditional operator).

For example, I was looking at some Ion Auth code:
Code:
if ($this->input->post('remember') == 1) {
                $remember = true;
            }
            else {
                $remember = false;
            }
Would anyone prefer this?
Code:
$remember = ($this->input->post('remember') == 1 ? TRUE : FALSE );
Or:
Code:
$remember = FALSE;
if ($this->input->post('remember') == 1)
{
    $remember = true;
}



If, then, else shorthand (aka ternary or conditional operator)? - El Forum - 10-20-2010

[eluser]richthegeek[/eluser]
All of them are too verbose - the input::post() method returns a boolean "false" if the item is not set (as is the case with unticked checkboxes).

As such, remember can just be something like the following (although the casting is unrequired)
Code:
$remember = (bool) $this->input->post('remember');



If, then, else shorthand (aka ternary or conditional operator)? - El Forum - 10-20-2010

[eluser]richthegeek[/eluser]
Just realised I answered a question that wasn't asked!

I like using the ternary operator for small things like this - if you need two ternary operators in one statement then you really should fall back to a standard if/elseif/else statement.


If, then, else shorthand (aka ternary or conditional operator)? - El Forum - 10-21-2010

[eluser]n0xie[/eluser]
We use both but for different forms of if. We try to make a difference between control structure and a simple check structure. A control structure decides the 'flow' of the application based on some checks. A simple check just evaluates some conditions to see if it should proceed with whatever it is doing.

Example:
Code:
// control structure
if (some condition is true)
{
  execute this piece of code
}
else
{
  do something completely different
}

// example in codeigniter
if ($this->form_validation->run() == FALSE)
{
  // show form
}
else
{
  // process submitted form
}

Code:
// simple check
$data = (isset($data)) ? $data : array();
$title = ($this->input->post($title)) ? $this->input->post($title, TRUE) : lang('untitled');