php

String interpolation and formation in PHP

We can easily format strings with variables in PHP. In the code snippet, we are formatting our string using variable name and using curly brackets.

<?php
    $name = "world";
    echo "Hello $name";
    //-> Hello World

    $arr = [
        'name' => 'John'  
    ];
    echo "My Name is '{$arr["name"]}'";
    //-> My Name is 'John'
?>

You need to use double quotes with your string to use variables inside it. You can directly use a variable with a string. Below is an example.

<?php
  $fruit = "Apple";
  $full_txt = "$fruit is sweet";
  echo $full_txt;
  // -> Apple is sweet
?>

The same can be done using curly brackets. Using the variable name in curly brackets.

<?php
  $fruit = "Apple";
  $full_txt = "{$fruit} is sweet";
  echo $full_txt;
  // -> Apple is sweet
?>
Was this helpful?