popsicle
popsicle

Reputation: 419

PHP echo format inside other variables

I've been trying to echo other variables inside a variable. I read other questions and pages about using ' and . to properly format in multiple different ways, but it only parsed some of them correctly.

From what I read, '.$var.''.$var2.' should have worked, then I tried '$var . $var2', '$var' . '$var2', and a few others. All returned errors.

PHP:

<?php
$path = "/img/";
$file = "photo.jpg";
$width = "300";
$height = "250";
$x = "<span class=\"showthis\" style=\"background-image: url($path $file); width: $width px; height: $height px\"></span>";
?>

I'm trying to understand how to format it in order to have two variables directly beside each other to parse without spaces.

<?php echo $x; ?>

as:

<span class="showthis" style="background-image: url(/img/photo.jpg); width: 300px; height: 250px;"></span>

I guess my question specifically, would be how to have two variables consecutively without spaces in them parsing.

Thank you for your help.

Upvotes: 0

Views: 354

Answers (3)

Dimitris Sapikas
Dimitris Sapikas

Reputation: 622

In general you have to use . between two string to "add" them it must be look like this :

$x = "<span class=\"showthis\" style=\"background-image: url(".$path.$file."); width: ".$width." px; height: ".$height." px\"></span>";

Upvotes: 1

bizzehdee
bizzehdee

Reputation: 21023

use braces to show that its a variable, and you can then put them next to each other

$x = "<span class=\"showthis\" style=\"background-image: url({$path}{$file}); width: $width px; height: $height px\"></span>";

Upvotes: 1

TaZ
TaZ

Reputation: 743

In this case you can simply remove the space.

$x = "<span class=\"showthis\" style=\"background-image: url($path $file); width: $width px; height: $height px\"></span>";

becomes

$x = "<span class=\"showthis\" style=\"background-image: url($path$file); width: $width px; height: $height px\"></span>";

Upvotes: 0

Related Questions