1. 13
    String interpolation & escaping in PHP
    1m 38s

String interpolation & escaping in PHP

Mark Shust
InstructorMark Shust

Share this video with your friends

Send Tweet
Published a year ago
Updated 6 months ago

Concatenating strings together can sometimes be hard to read. As an alternative, you can use string interpolation to output variables within strings in PHP.

Instructor: [0:00] Now that we've learned about concatenating strings, there's yet another way to combine multiple variables together, and that's using something called string interpolation. This can be useful when dealing with strings that need to be output similar to this numPost display variable, where we are combining two values together with a space.

[0:19] It can be a bit difficult to understand how the string will be formatted since we have a space within one of these outputted values, and there is a space on either side of this period.

[0:34] Let's surround this entire variable assignment within double quotes, and then we will remove the single quotes, as well as the period. Wow, it's pretty easy to tell how this string will be formatted now. When we refresh the page, nothing changes.

[0:53] This isn't possible when we use single quotes, but when we use double quotes, we can interpolate, which means we can evaluate a variable defined within a string. This can greatly simplify the cognitive load when dealing with strings that are to be outputted.

[1:08] If we wanted special characters within this string, we can escape them with a backslash. For example, if we wanted to surround this number 10 within double quotes, we can enter a backslash here to escape this string and then enter our special character, which is a double quote. We will do it again after this variable.

[1:30] When we save and refresh, we will now see our string and our number 10 enclosed in double quotes.