Print associative array element inside string without concatenation

Asked

Viewed 660 times

2

I have to print out a tag HTML via a echo with the value of a array associative, however I can’t make it print to be concatenative use.

Code .php (this way is not working, I believe by the quotes that involves 'name')

echo '<span class="video">{$video['nome']}</span>'
  • @Qmechanic73, this works however when doing: echo '<span class="video">{$video['name']}</span>' does not capture the value of the array at the name position, an error is returned

2 answers

2


Interpolation of string only works when you use double quotes. But it has the drawback of having to use single quotes 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>';

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Documentation.

I had already said something about this in that reply.

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

  • ,@bigown, this way would change all double quotes present within html as this class='video' that you changed from double quotes to single

  • Exactly. I’m seeing if there’s any other solution.

  • ,@bigown, I will use concatenation since it is a better solution than to exchange all single quotes for doubles. so the simplest way is: echo '<span class="video">. $video['name']. </span>'

  • @Ricardohenrique found another solution. I don’t know if it is to your advantage but now you have three options.

  • ,@bigown, had already checked this way to create strings (with similar functioning the <pre> tags) but there was no thinking is to use them for this since rarely seen being used

1

According to the documentation that nay it is possible.

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

Note: Unlike the syntax for double quotes and heredoc, variables and escape sequences for special characters will not be replaced when they occur inside strings between quotes.

What you can do is use same concatenation.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.