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?
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.
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 _ )
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With