PHP Strings

A string is a series of characters, surrounded by quotes or special syntax. A string can be created using single quotes or double quotes.

Strings can be used with echo statements to display the strings in the browser.

<?php 
  // echo a string with double quotes
  echo "Hello World <br>";
  
  // echo a string with single quotes
  echo 'Hello World <br>'; 

Strings can also be used with variables.

<?php
  // setting the variables to strings
  $greeting = "Hello";
  $target = "World";

  // combine variables together with a string
  $phrase = $greeting . " " . $target;
  echo $phrase;

Variable Substitution

In the previous example, the period was used to concatenate or combine the strings together. But PHP allows for variable replacement or variable substitution, which will output variables that are embedded into string literals.

NOTE

Variable substitution only works with double-quotes. It does not work with single quotes.

<?php
  // using variable substitution
  echo "$phrase Again <br>";

  // try it with single quotes
  echo '$phrase Again <br>';

When using variable substitution, it is encouraged to wrap the variable in a set of curly braces ({ }). This will let PHP know where the variable starts and stops.

<?php
  // using variable substitution with curly braces
  echo "{$phrase}Again <br>";