PHP Strings


String is a sequence of characters, numbers, written within double quotes or single quotes during declaration. A string can hold letters numbers and special characters. Example :
<?php

  $str1 = 'Hello world This is String one';
  $str2 = "Hello world This is String two"; 

  echo $str1 . "<br/>";
  echo $str2 . "<br/>";

?>
Output :

Hello world This is String one
Hello world This is String two

Difference Between single and double quotes :

The main difference between using the single and double quotes is that the double quotes replaces variables with the string representations of their values as well as specially interpreting certain escape sequences, while singly quoted strings are treated almost literally.
<?php

  $var = "PHP Tutorial";
  
  $str1 = 'This is String one from $var';
  
  $str2 = "This is String two from $var"; 

  echo $str1 . "<br/>";
  echo $str2 . "<br/>";

?>
Output :

This is String one from $var
This is String two from PHP Tutorial

At the above example the variable $str1 with single quote, does not print the $var variable, but $str2 prints the $var data.

The escape-sequence replacements in php are as follows :

\n :  newline character
\r :  carriage-return character
\t :  tab character
\$ :  dollar sign itself ($)
\" :  single double-quote (")
\\ :  single backslash (\)

Example :
<?php

  echo "New Line Character \n";
  echo "Carriage-Return Character \r";
  echo "Tab Character \t";
  echo "Dollor sign \$";
  echo "Single-double quote \"";
  echo "Single BackSlash \\";

?>

String Concatenation Operator : 

PHP has two operators that are specially designed for strings operations. These are :

Concatenation ( . ) : Used to concate the two string variables. Example :
 echo $str1 . str2;
Concatenation Assignment ( .= ) : Used to appends one string variable in another. Example :
 $str1 .= $str2;
Example :
<?php

  $str1 = "This is String One.";
  $str2 = "This is String Two.";

  echo $str1 . $str2; // Concatenation operator
  echo "<br/>";
  $str1 .= $str2; // Concatenation Assignment operator
  echo $str1;

?>
Output :

This is String One.This is String Two.
This is String One.This is String Two.


Next Topic :