Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP string interpolation syntax

Tags:

I tried to do redirect with this syntax:

header("location: readMore.php?id=$post['post_id']");

But it didn't work. It worked only after someone suggested to put curly brackets around $post['post_id']!

The correct syntax is:

header("location: readMore.php?id={$post['post_id']}");

What does the curly brackets do in this case?

like image 250
Pioneer2017 Avatar asked Apr 16 '17 12:04

Pioneer2017


People also ask

Does PHP have string interpolation?

PHP String formatting String interpolationYou can also use interpolation to interpolate (insert) a variable within a string. Interpolation works in double quoted strings and the heredoc syntax only. $name = 'Joel'; // $name will be replaced with `Joel` echo "<p>Hello $name, Nice to see you.

What is variable interpolation in PHP?

Variable interpolation is adding variables in between when specifying a string literal. PHP will parse the interpolated variables and replace the variable with its value while processing the string literal.

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.

What is PHP heredoc used for?

Heredoc is one of the ways to store or print a block of text in PHP. The data stored in the heredoc variable is more readable and error-free than other variables for using indentation and newline. How the heredoc content can be stored in a variable or printed has shown in this tutorial.


2 Answers

Quoting the manual:

When a string is specified in double quotes or with heredoc, variables are parsed within it.

There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort.

The complex syntax can be recognised by the curly braces surrounding the expression.

Your first code uses simple syntax, and your second code uses a complex one.

The manual does not explicitly state this, but whitespace in simple syntax seems to be an error, rendering your first code invalid. Complex syntax appears to support the same syntax as regular PHP does as far as I can see, but again this does not seem to be actually guaranteed anywhere.

String interpolation is quite flunky in general:

$a = [['derp']];
$b = $a[0];

// Works. It prints derp
echo "$b[0]";

// Doesn't work. It throws an error
echo "$b[ 0 ]";

// Works. It prints derp
echo "{$b[ 0 ]}";

// Doesn't work. It prints Array[0]
echo "$a[0][0]";

// Works. It prints derp
echo "{$a[0][0]}";

// Doesn't work. It prints { Array[0] }
echo "{ $a[0][0] }";

You get similar issues with $object -> foo and $object->foo->bar.

To me, that is pure madness. For that reason I've come to avoid double quoted strings whenever possible (the only thing I used them for are for escape sequences like "\n"). I instead use single quotes and string concatenation, like so:

header( 'location: readMore.php?id=' . $post[ 'post_id' ] );

This lets you use actual PHP syntax for variables without the horrible death trap that is string interpolation.

like image 105
Siguza Avatar answered Sep 21 '22 14:09

Siguza


I came to this question to know more about constant interpolation syntax when those PHP "<<<" things are used to create multiline strings called Heredocs (which allow variable interpolation, unlike Nowdocs).

However, it seems there is no specific syntax for them, and therefore a simple workaround is to create a closure to do so. In here it is just an anonymous function assigned to a variable that will be invoked with parameters:

$int = 'intruder';        // Variable
define('con', '"smart"'); // Constant
// For complex interpolation:
// 1. Define a closure (anonymous function)
// 2. Assign it to a variable with a short name (e.g.: _ )
// 3. Invoke the function by calling the variable with parameters enclosed in ()
$_ = function ($val){return $val;};

$doc = <<<TXT
Hi there,
One day I caught this $int nearby.
I was then told that actually other {$_(con)} $int was there before.
So who came first, the chicken or the egg?
TXT;                      // Heredoc
echo $doc;

Output:

Hi there,

One day I caught this intruder nearby.

I was then told that actually other "smart" intruder was there before.

So who came first, the chicken or the egg?

You can test the above online on 3v4l. This was based on this answer with a few more examples with operations inside the interpolation brackets.

like image 43
Armfoot Avatar answered Sep 22 '22 14:09

Armfoot