Skip to content
Advertisement

Interpret PHP inside a quote in a PHP

I have this variable $url that I need to print inside a quoted HTML that it’s inside a PHP if conditional.

<?php 
$url = $thumb['0']; 
if ( in_category( 'News' )) {
    //nothing here
} else {
    echo '<div class="image-holder"><img src="$url;" alt="Post photo" class="image-border"></div>';
}
?>

But src="$url;" is interpreted as src="$url;" in the HTML code. It does not interpret as a variable.

How can I solve that?

Advertisement

Answer

I like to seperate the business logic from the output. This, in combination with PHP’s alternative syntax for control structures, keeps your HTML output clean and easily readable.

See this example:

<?php
// Do some things here
$url = $thumb['0'];

// Below this point we output HTML
// Only use simple control structures here, this keeps your HTML clean and easy to read
?>

<?php if (in_category('News')): ?>

<?php else: ?>
<div class="image-holder"><img src="<?php echo $url; ?>" alt="Post photo" class="image-border">
</div>
<?php endif; ?>

Since the first part of the if-statement is empty, you can simplify the code:

<?php if (!in_category('News')): ?>
<div class="image-holder"><img src="<?php echo $url; ?>" alt="Post photo" class="image-border">
</div>
<?php endif; ?>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement