Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: variables in strings without concatenation

Tags:

string

php

If I have a variable $var in this string: echo "Hello, there are many $vars";

Php looks for the variable $vars instead of $var.

Without concatenation like: "Hello, there are many $var" . "s";
is there another way to do this, like some sort of escaping character?

like image 428
dukevin Avatar asked Aug 12 '11 07:08

dukevin


People also ask

What is Heredoc and Nowdoc in PHP?

Heredoc and Nowdoc are two methods for defining a string. A third and fourth way to delimit strings are the Heredoc and Nowdoc; Heredoc processes $variable and special character but Nowdoc does not processes a variable and special characters.

Which is the right way of declaring a variable in PHP?

A variable starts with the $ sign, followed by the name of the variable. A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )


2 Answers

In php you can escape variables like so

echo "Hello, ${var}'s head is big";

or like

echo "Hello, {$var}'s head is big";

Reference here under escape character section

like image 66
Tristan Avatar answered Sep 21 '22 13:09

Tristan


You can use {} to escape your variable properly. Consider the following example:

echo "There are many ${var}s"; #Or...
echo "There are many {$var}s";

Working example

like image 26
Madara's Ghost Avatar answered Sep 18 '22 13:09

Madara's Ghost