Print associative array element within string without concatenation

2

I have to print an tag HTML through a echo with the value of an associative array, but I can not get it to print using concatenation.

Code .php (this way it is not working, I believe the quotation marks that surround 'name')

echo '<span class="video">{$video['nome']}</span>'
    
asked by anonymous 25.01.2015 / 13:14

2 answers

2

String interpolation only works when you use double quotation marks. But it has the drawback of having to use single quotation marks elsewhere. You can also use NowDoc. See the examples below:

$video = array('nome' => 'teste');
echo "<span class='video'>{$video['nome']}</span>";
echo <<<FIM
<span class='video'>{$video['nome']}</span>
FIM;
echo '<span class="video">' . $video['nome'] . '</span>';

See running on ideone .

Documentation .

I've already been saying something about it in that answer .

But on second thought, is there any reason not to do concatenation? I think you should review this requirement.

    
25.01.2015 / 13:22
1

According to documentation no is possible.

  

To specify a single literal quote, escape it with a slash   inverted (). To specify a backslash, double-click (\).   All other backslash instances will be treated as one   literal backslash: this means that the other   exhaust that you can use to, such as \ r or \ n, will be issued   literally, as specified instead of having any meaning   special.

     

Note: Unlike the syntax for double quotation marks , and

a href="http://www.php.net/manual/en/language.variables.php"> variables and   escape sequences for special characters will not be replaced   when they occur inside quoted strings.

What you can do is to use concatenation yourself.

$video['chave'] = "valor";
echo '<span class="video">{' .$video['chave'] .'}</span>';
    
25.01.2015 / 13:49