medk
medk

Reputation: 9549

Condition inside variables

I have this example which works great:

$text = 'Lorem Ipsum';

$html = <<<HTML
<div>
   <span>$text</span>
</div>
HTML;

Now how to do this the right way to get option 2 selected:

$val = 2;

$html = <<<HTML
<select>
   <option if ($val == 1) {echo 'selected';} >Option 1</option>
   <option if ($val == 2) {echo 'selected';} >Option 2</option>
   <option if ($val == 3) {echo 'selected';} >Option 3</option>
</select>
HTML;

Upvotes: 0

Views: 109

Answers (2)

Nisse Engstr&#246;m
Nisse Engstr&#246;m

Reputation: 4752

You have to move the if statements out of the heredoc:

$sel1 = $sel2 = $sel3 = '';

     if ($val == 1) $sel1 = ' selected';
else if ($val == 2) $sel2 = ' selected';
else if ($val == 3) $sel3 = ' selected';

$html = <<<HTML
<select>
   <option$sel1>Option 1</option>
   <option$sel2>Option 2</option>
   <option$sel3>Option 3</option>
</select>
HTML;

You can shorten the if/else ladder by using variable variables:

$sel1 = $sel2 = $sel3 = '';

${"sel$val"} = ' selected';

$html = <<<HTML
<select>
   <option$sel1>Option 1</option>
   <option$sel2>Option 2</option>
   <option$sel3>Option 3</option>
</select>
HTML;

You can also shorten the empty string assignments by using an array:

$sels = array_fill (1, 3, '');

$sels[$val] = ' selected';

$html = <<<HTML
<select>
   <option{$sels[1]}>Option 1</option>
   <option{$sels[2]}>Option 2</option>
   <option{$sels[3]}>Option 3</option>
</select>
HTML;

Note: The above is untested; I typed it in on my phone.

Upvotes: 0

pilec
pilec

Reputation: 513

I think this is the work for template engine - but don`t worry, is pretty easy to use.

Only thing you need is prepared project with composer and after that easily install one of the template engine (for this example I picked up Latté).

Install of composer:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php

after that installing Latté:

php composer.phar require latte/latte

And on the end, you can create something like this:

$latte = new \Latte\Engine;

$latte->setTempDirectory('/path/to/tempdir');

$parameters['val'] = 2;

$html = $latte->renderToString('template.latte', $parameters);

and put this content into file "template.latte" in same directory:

<select>
{foreach [1, 2, 3] as $key}
    <option {if $val === $key}>Option {$key}</option>
{/foreach}
</select>

This solution is used by professionals for many reasons:

  1. put logic and rendering side by side, does not mixed things up.
  2. All variables are automatically escaped (to avoid XSS)
  3. DRY (Do not Repeat Yourself) principe, that row with option should be written only once

BTW you always should use triple equals in condition in PHP (compares also type of variable). Its much more safe and you can save a lot of time of debug using this principle :-).

Upvotes: 1

Related Questions