Search code snippets, questions, articles...

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'
?>
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

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?
0 Comments