Welcome Guest, Not a member yet? Register   Sign In
If, then, else shorthand (aka ternary or conditional operator)?
#1

[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;
}
#2

[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');
#3

[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.
#4

[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');




Theme © iAndrew 2016 - Forum software by © MyBB