Pradeep G
Pradeep G

Reputation: 139

why cant i add php code inside a option tag?

I'm a newbie working on a project in php. I am trying to add a php code inside a html option tag. here is what I'm doing...

$companies = Company::find('all');
foreach ($companies as $c)
{
  echo "<option value='".$c->id."' ".if($c->id == $companyselected){'selected'}.">".$c->name."</option>" ;
}

$companyselected is the variable I pass from the controller which contains the id of the company that should be displayed at the top of the dropdown. It outputs nothing. why cant i add like this.Is this correct to add like this.I'm stuck with this for long time. please help me out guys

Upvotes: 2

Views: 112

Answers (5)

Gyaneshwar Pardhi
Gyaneshwar Pardhi

Reputation: 471

use this

$companies = Company::find('all');

$selected= '';

foreach ($companies as $c)
{
    if($c->id == $companyselected){
        $selected='selected';
    }
    echo "<option value='".$c->id."' ".$selected." >".$c->name."</option>" ;
}

Upvotes: 0

Code Lღver
Code Lღver

Reputation: 15603

Try this:

echo "<option value='".$c->id."' ".(($c->id == $companyselected) ? 'selected=selected':'').">".$c->name."</option>" ;

EDITED

$str = "<option value='".$c->id."' ";
$str .= (($c->id == $companyselected) ? "selected='selected'":"");
$str .= ">".$c->name."</option>" ;
echo $str;

Upvotes: 2

Anshad Vattapoyil
Anshad Vattapoyil

Reputation: 23463

Try this, You can't use if statement in echo.

$companies = Company::find('all');
foreach ($companies as $c)
{
    if($c->id == $companyselected) {
        echo "<option value='".$c->id."' selected='selected'>".$c->name."</option>" ;
    } else {
        echo "<option value='".$c->id."'>".$c->name."</option>" ;
    }
}

Or

foreach ($companies as $c)
{
   $selected = ($c->id == $companyselected) ? 'selected' : '';
   echo "<option value='".$c->id."' ".$selected.">".$c->name."</option>" ;
} 

Upvotes: 0

Vineesh
Vineesh

Reputation: 467

This is the write way to do this.

$companies = Company::find('all');
foreach ($companies as $c)
{
         echo "<option value='".$c->id."' ";
         if($c->id == $companyselected){
              echo 'selected';
         }
         echo ">".$c->name."</option>" ;
}

Upvotes: 0

JTC
JTC

Reputation: 3464

You should do it like this:

Use ternary operator

foreach ($companies as $c)
  {
   $selected = ($c->id == $companyselected) ? "selected='selected'" : "";
   echo "<option value='".$c->id."' ".$selected.">".$c->name."</option>" ;
  } 

Upvotes: 0

Related Questions