1

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>';
1
  • Do you logic before your echo statement and store the results in a variable. Then echo it out normally in your echo statement. Commented Jun 26, 2014 at 14:53

2 Answers 2

5

Use a ternary operator

<?php echo '<span class="time">'.$created_time.(isset($heroloc) ? '@ '.$heroloc : '').'</span>';
Sign up to request clarification or add additional context in comments.

4 Comments

it won't echo NULL, it's just NULL
I know it won't actually output anything, but I'm just wondering why you'd write that. '' would be much more appropriate.
You should use an empty string '' instead of null.
Ok fair enough, I updated my answer :) Though I'm not sure I understand why one is more appropriate than another.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.