PHP - Strings


They are sequences of characters, like "PHP supports string operations".

NOTE − Built-in string functions is given in function reference PHP String Functions

Following are valid examples of string

$string_2 = "This is a somewhat longer, singly quoted string";


Live Demo
   $variable = "name";
   $literally = 'My $variable will not print!\\n';
   print "<br />";
   $literally = "My $variable will print!\\n";

This will produce the following result −

My $variable will not print!\n
My name will print!\n

There are no artificial limits on string length - within the bounds of available memory, you ought to be able to make arbitrarily long strings.

Strings that are delimited by double quotes (as in "this") are preprocessed in both the following two ways by PHP −



The escape-sequence replacements are −

  • \n is replaced by the newline character
  • \r is replaced by the carriage-return character
  • \t is replaced by the tab character
  • \" is replaced by a single double-quote (")
  • \\ is replaced by a single backslash (\)

String Concatenation Operator


Live Demo
   $string1="Hello World";
   echo $string1 . " " . $string2;

This will produce the following result −

Hello World 1234


Between the two string variables we added a string with a single character, an empty space, to separate the two variables.

Using the strlen() function


Let's find the length of our string "Hello world!" −

Live Demo
   echo strlen("Hello world!");

This will produce the following result −


The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string)

Using the strpos() function



Let's see if we can find the string "world" in our string −

Live Demo

This will produce the following result −


As you see the position of the string "world" in our string is position 6. The reason that it is 6, and not 7, is that the first position in the string is 0, and not 1.