-2

I am trying to pass a simple php value to html but I cannot format it in the right way. How can I do this?

<?php
 
$html = '

<img src="'$val'.svg" alt="15"> //Does not work

';

$val = 5;
?>
Hamdi
  • 187
  • 1
  • 2
  • 11
  • You need to use double quotes if you want to include variables in a string... `"$val"` will be extracted to the variables value – Gowire Apr 08 '21 at 12:57
  • Duplicate of https://stackoverflow.com/questions/6670879/can-i-echo-a-variable-with-single-quotes#:~:text=Taken%20from%20php.net%3A%20%22,is%20no%20you%20can't. – esqew Apr 08 '21 at 12:58
  • This won't work if you define `$val` *after* the string you want to use it in though… – deceze Apr 08 '21 at 12:58
  • also `$val` defined after use it ? – Devsi Odedra Apr 08 '21 at 12:58
  • I's say [that answer](https://stackoverflow.com/a/3446286/1066240) would be the better reason as a duplicate. – biesior Apr 08 '21 at 13:01
  • I used double quotes but that does not seem to work. – Hamdi Apr 08 '21 at 13:01
  • 1
    "*I used double quotes but that does not seem to work*" as already @deceze and Devsi pointed you you are trying to use variable **before** assigning it, move it higher, also read linked answers how to join variables in the strings. Bonus TIP: if you were using any good IDE, it would tell you a warning about using an unassigned variable. `$val = 5; $html = "15";` – biesior Apr 08 '21 at 13:05
  • Bonus tip 2: do not use `?>` for terminating the PHP script, although it's valid and allowed in may cause some troubles in the longer run, especially when you'll try to modify headers. 1: https://stackoverflow.com/q/8028957/1066240 scroll to *Whitespace after ?>* – biesior Apr 08 '21 at 13:11

1 Answers1

1

You would try to format it this way:

<?php
        $val = 5;
        $html = "<img src='${val}.svg' alt='15'> ";
    ?>