one line if statement?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pinehead18
Forum Contributor
Posts: 329
Joined: Thu Jul 31, 2003 9:20 pm

one line if statement?

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Search for the term ternary operator in the manual.
User avatar
webgroundz
Forum Commoner
Posts: 58
Joined: Thu Jun 21, 2007 1:20 am
Location: Philippines

Post by webgroundz »

here's my sample code snippet:

Code: Select all

count($this->getErrorMessages())) ? FALSE : TRUE;
:) :) :)
User avatar
yacahuma
Forum Regular
Posts: 870
Joined: Sun Jul 01, 2007 7:11 am

HtmlOption Class

Post 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
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post 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?
Post Reply