Page 1 of 1

one line if statement?

Posted: Tue Jul 31, 2007 8:14 pm
by pinehead18
this is my current if statement <OPTION". if($section == "events") {echo "selected"; } .">Events</OPTION>

and it does not like it, isn't there someway for like a short hand if statement?

Thanks

Posted: Tue Jul 31, 2007 8:21 pm
by feyd
Search for the term ternary operator in the manual.

Posted: Tue Jul 31, 2007 8:29 pm
by webgroundz
here's my sample code snippet:

Code: Select all

count($this->getErrorMessages())) ? FALSE : TRUE;
:) :) :)

HtmlOption Class

Posted: Tue Jul 31, 2007 8:31 pm
by yacahuma
This is where you can use a nice little class

put this code in a separate file HtmlOptionLib.php

Code: Select all

class HtmlOption
{
		
    function toHtml($name,$val,$options, $extra="",$isEditable=true,$size=1)
    {
        echo HtmlOption::toStr($name,$val,$options, $extra,$isEditable,$size);
    }
    function toStr($name,$val,$options, $extra="",$isEditable=true,$size=1)
    {
		
		    if ($isEditable)
				{
        $str="<select name='{$name}' id='{$name}' size='$size' $extra>\n";
        foreach ($options as $key => $value)
        {
	        $sel = ( strcmp($key,$val) == 0) ? ' selected="selected"' : '';
          $str .="     <option value='$key'{$sel}>". $value ."</option>\n";
	      }	
       $str .="</select>\n";
       return $str;
			 }
			 else
			 {
			  $value = $options[$val];
			  return "<input readonly=\"readonly\" type=\"text\" name=\"{$name}\" value=\"{$value}\" >";
			 }
 	 }
}//end of class
the you can do something like

Code: Select all

require_once 'HtmlOptionLib.php';
$options = array('5'=>'Car','6'=>'Dog','9'=>'Wahtever');//always key=> value array
HtmlOption::toHtml('myvalue',9,$options);
This really simplifies your code IMHO

Posted: Wed Aug 01, 2007 7:19 am
by superdezign
webgroundz wrote:here's my sample code snippet:

Code: Select all

count($this->getErrorMessages())) ? FALSE : TRUE;
:) :) :)
Why do you have false before true in the ternary statement...? And why so many closing parentheses?