Barrard
Barrard

Reputation: 2043

Why this line of code doesn't need escaped quotes

I'm following a PHP tutorial, and came accross this line of code

redirect_to("manage_content.php?subject={$current_subject["id"]}");

I was surprised to see this works without the need to escape the quotes around "id" inside the brackets.

But I don't understand why. Does anyone know?

Upvotes: 3

Views: 45

Answers (1)

Jeff
Jeff

Reputation: 799

When you wrap a variable in curly braces {}, the PHP parser knows anything inside that is a variable and won't parse it like the rest of the string!

This only works with strings in double-quotes - single-quoted strings are taken at face value, so this has to be escaped:

$str = 'My cool string! {$array[\'key\']}';

While your example doesn't.

Because of this, it's best practice to put static strings in single quotes - it's a micro-optimization, but it's technically a bit faster since the PHP parser doesn't have to work its way through the string!

Upvotes: 4

Related Questions