Welcome Guest, Not a member yet? Register   Sign In
Ternary vs. Long method condition
#1

[eluser]aroman[/eluser]
Heres the scenario:
Code 1:
Code:
$tmptitle = $this->input->post( 'title' );
if ( !empty($tmptitle) )
{
   $title = $tmptitle ;
}
else
{
  if ( !empty($bannerads->title) )
  {
     $title = $bannerads->title ;
  }
  else
  {
     $title = '' ;
  }
  
  echo $title ;
}


Code 2:
Code:
$title = !empty($tmptitle) ? $tmptitle : !empty($bannerads->title) ?  ($bannerads->title) : '' ;
echo $title ;

Executing the code#1, it works howver when executing the Code#2 i received an error. It says "Severity: Notice
Message: Trying to get property of non-object ..."
Is this a bug in ternary operation or in CI ?

Thanks
-armano
#2

[eluser]Dam1an[/eluser]
a) That snippet of code there isn't really anything to do with CI, so not a CI problem
b) Nested ternaries are just messy Wink
c) What happens if you but brackets around the nested part?
#3

[eluser]aroman[/eluser]
@dam1a , yeah nested ternaries are messy if it is very long..but in these case, i would love to use the ternary.
i havnt put a bracket[] yet, is it possible?? hmm, where should i put it ? can you show me how?

thanks
#4

[eluser]Dam1an[/eluser]
A little bit of laying around with it, and the only way I could get it to fail was with
Code:
$title = !empty($tmptitle) ? $tmptitle : !empty($bannerads->title) ?  ($bannerads->title) : '';
var_dump($title);

But adding brackets to the nested part like so
Code:
$title = !empty($tmptitle) ? $tmptitle : (!empty($bannerads->title) ?  ($bannerads->title) : '');
var_dump($title);

fixes it Smile (I tried all paths and it works fine for me)
#5

[eluser]aroman[/eluser]
Hi dam1an, it works now..thank you so much..im wondering why we need to put a bracket for the second else part, however in the first part dont have it..hmmm.
#6

[eluser]Dam1an[/eluser]
In the first part you don;t need to, as it's just a single, atomic value, instead of an expression
I think you eed brackets for the second part, as it will probably just assume !empty($bannerads->title) is the else part of the statement, instead of actually doing the whole of the else part, but the bracket forces it to do so
#7

[eluser]Bogdan Tanase[/eluser]
aroman, are you sure you'll understand a month from now what you did there ? Smile

ternaries are very useful for simple expressions; using it like that is just plain bad ... IMHO




Theme © iAndrew 2016 - Forum software by © MyBB