Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does { } do within a string?

Tags:

php

$name = "jason";
$p = "hello-{hello2}-$name-{$name}";
echo $p;

output :

hello-{hello2}-jason-jason

Came across some examples of prepared statements and noticed this. If its encompassing a variable, it removes them, otherwise it keeps them. Why is this behavior necessary when

echo "$name";

gets you the same result as

echo "{$name}";

or is it just readability?

like image 791
jason Avatar asked Sep 30 '14 15:09

jason


People also ask

What is a string in Python?

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1.

What is a string in C?

A string is an object of type String whose value is text. Internally, the text is stored as a sequential read-only collection of Char objects. There is no null-terminating character at the end of a C# string; therefore a C# string can contain any number of embedded null characters ('\0').

What is substring in C++?

Substring in C++. In C++, std::substr() is a predefined function used for string handling. string.h is the header file required for string functions.

What is the use of string find in C++?

string find in C++. String find is used to find the first occurrence of sub-string in the specified string being called upon. It returns the index of the first occurrence of the substring in the string from given starting position.


1 Answers

It's used as a delimiter for variables in strings. This is necessary in some cases, as PHP's string parser isn't Greedy aand will mis-interpret many common structs.

e.g.

$foo = array();
$foo['bar'] = array();
$foo['bar']['baz'] = 'qux';

echo "Hello $foo[bar][baz]";

will actually print

Hello Array[baz]

Because it's parsed as

echo "Hello ", $foo['bar'], "[baz]";
        ^          ^           ^
      string     array       string

Using {} forces PHP to consider the array reference as single entity:

echo "Hello, {$foo['bar']['baz']}";  // prints "Hello, qux"

It also helps differentiate ambiguous stuff

$foo = 'bar';

echo "$foos" // undefined variable 'foos'
echo "{$foo}s" // variable containing 'bar' + string 's'
like image 156
Marc B Avatar answered Oct 02 '22 10:10

Marc B