cover

It is used to Insert variable in the String. You can call this as alternative to string concatenation. Using String Interpolation you can concatenate n number of string and variable

If we have to concat two string and variable. We use dot(.) to concat string in php.

Concatenation without using String Interpolation #

<?php
    $name = "Nitish Kumar";
    $greeting = "Hi " . $name;
    
    echo $greeting;
    //      ↓
    // Hi Nitish Kumar

?>

Concatenation using String Interpolation #

We can do this without using dot(.) also i.e String Interpolation. String Interpolation makes our code more readable.

<?php
    $name = "Nitish Kumar";
    $greeting = "Hi $name";
    
    echo $greeting;
    //      ↓
    // Hi Nitish Kumar

?>

As Now you now String Interpolation. You need not to us dot(.) anymore to concat the string with variable.

String Interpolation is very useful because it makes our code more readable. I can’t imagine my life without string Interpolation. It is very difficult to maintain pair of double quote followed by dot(.) to add add variable.

Complex Curly Syntax #

Complex Curly Syntax is used to interpolate complex expression inside the string.

<?php
    $num = 2;
    
    $attemp1 = "Square of $num =  $name * $num";
    echo $attemp1;
    //      ↓
    // Square of 2 = 2 * 2

    // but I want to evalute the expression.

    // to do so. We can use `Complex Curly Syntax`

    $attempt2 = "Square of $num =  {$name * $num}"
    echo $attemp1;
    //      ↓
    // Square of 2 = 2 * 2


?>

It is called as Complex Curly Syntax because it can interpolate complex expression.

Example 2 #

When you have a to concat 5-10 variable then code readability becomes the problem. I am not saying that string interpolation is mandatory thing but it is something which we must use to increase our code quality.

See this example to get more idea. This example with make more sense to you. How code readability become problem when you have a giant string concatenation.

<?php
    $name = "Nitish Kumar";
    $age = 20;
    $gender = "India";

    // Without String Interpolation
    $bio = "<p>My name is " . $name . ".</p><p>I'm " . $age . " years old.</p><p> I am from " . $country . ".<p>";
    
    // With String Interpolation
    $bio = "<p>My name is $name .</p><p>I'm $age years old.</p> <p>I am from $country .</p>";

?>

BTW, You can write code without String Interpolation also but I assume you will not do so.