RonnieT
RonnieT

Reputation: 2203

Insert PHP into Echo

I am trying to insert the below PHP into an echo but having trouble with the correct formatting.

PHP:

<?php if ( isset($heroloc) ) { echo '@ '.$heroloc;} ?>

Would like to place the if statement into the below right after $created_time

echo '<span class="time">'.$created_time.'</span>';

Somethign like this, but formatted properly:

echo '<span class="time">'.$created_time. if ( isset($heroloc) ) { echo '@ '.$heroloc;'</span>';

Upvotes: 1

Views: 139

Answers (2)

Reactgular
Reactgular

Reputation: 54771

You can write it different ways.

Don't forget how handy sprintf can be.

$when = sprintf(isset($hereloc) ? '%s @ %s' : '%s', $created_time, $hereloc);
echo "<span class='time'>$when</span>";

The ternary operator

echo '<span class="time">'.$created_time.(isset($heroloc) ? '@ '.$heroloc : '').'</span>'

But, the correct approach is to not mix logic and HTML output. Instead, ensure $hereloc is always valid before the echo.

// put your rules in a controller.php file
// ensure your view receives all required variables. 
$hereloc = isset($hereloc) ? " @ $hereloc" : '';

// then separate your echo statements to a view.php file
echo "<span class='time'>{$created_time}{$hereloc}</span>";

This approach makes reading your view.php must easier.

Upvotes: 1

Dan
Dan

Reputation: 9468

Use a ternary operator

<?php echo '<span class="time">'.$created_time.(isset($heroloc) ? '@ '.$heroloc : '').'</span>';

Upvotes: 5

Related Questions