0

For you guys, I imagine this will be easy.

<div class="vote_pct" style="width: $widthpx;">

I want the variable to be $width and for it to have px on the end. If i put a space, it doesnt work. If i put them together, it treats it as one big variable name.

Could I ask someone the correct snytax to achieve this? Thanks

4 Answers 4

2
  • $bla = '<div class="vote_pct" style="width: '.$width.'px;">';

or

  • $bla = "<div class=\"vote_pct\" style=\"width: ${width}px;\">";
Sign up to request clarification or add additional context in comments.

3 Comments

:) or: $bla = "<div class='vote_pct' style='width: $width px;'>";
@galambalazs: you need to escape variables if you inserting them to a string.
@fabrik no you don't. Double quotes allow that. Check before you argue... :)
1

If you mix PHP and HTML you can do:

//PHP in HTML
<div class="vote_pct" style="width: <?php echo $width; ?>px;">

HTML in PHP
print '<div class="vote_pct" style="width: ' . $width . 'px;">';

1 Comment

Oh dear, I totally forgot to echo it. What am i doing? Awful error to make. Sillyness! Cheers bud
1
echo '<div class="vote_pct" style="width: '.$width.'px;">';

or

$width = 5;

echo "<div class=\"vote_pct\" style=\"width: {$width}px;\">";

Comments

0
<?php echo sprintf('<div class="%s" style="width: %spx">','vote_pct',$width);?>

3 Comments

changed, im sure he would of found that out anyways :)
echo sprintf() is an "antipattern". There is absolutely no reason that anyone should ever write echo sprintf() in any code for any reason -- it should be printf() every time.
Separating the literal string vote_pct as a parameter of sprintf() is just weird and unnecessary. The literal string should be simply written in the first parameter. This unexplained answer is not teaching best practices.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.