PHP Strings


What is String in PHP ?

A string is set of characters, like "This is string", Every character is same as byte. Simple way of define string in single quotes or double quotes like 'Testing' OR "Testing".

    A string canbe defined by following ways
  • single quoted
  • double quoted
  • heredoc syntax
  • nowdoc syntax

single quoted

Simple way to specify a string in single quotes('')

$string ='Hello test';

1. Example

echo 'this is a test string';
// Outputs : this is a test string

echo 'this is a 
test string in
multiline';
// Outputs : this is a test string in multiline

echo 'it\'s fine';
// Outputs : it's fine

echo 'Hi this is test \n a newline string';
// Outputs : Hi this is test \n a newline string

echo 'Variables do not use in single quotes $abc';
// Outputs : Variables do not use in single quotes $abc

double quoted

A strig is enclosed in double quotes ("")

2. Example

echo "this is a test string";
// Outputs : this is a test string

echo "this is a 
test string in
multiline";
// Outputs : this is a test string in multiline

echo "it\'s fine";
// Outputs : it's fine

echo "Hi this is test \n a newline string";
// Outputs : Hi this is test a newline string

$abc=5;
echo "Variables can use in double quotes $abc";
// Outputs : Variables can use in double quotes 5

Complex (curly) syntax

It is allow use of complex expressions.

3. Example

$test = 'curly sytax';

// It will not work because space is not allowed between curly brace and variable name.
echo "This is { $test}";
//Output :: This is { curly sytax} 

echo "This is {$test}";
//Output :: This is curly sytax

$array = array('k'=>'curly sytax');
echo "It works {$array['k']}";
//Output :: It works curly sytax

Escaped characters

Sequence Name Descrption
\n linefeed (replaced by newline character)
\r carriage return (replaced by carriage-return character)
\t horizontal tab (replaced by tab character)
\v vertical tab
\e escape
\f form feed
\\ backslash
\$ dollar sign
\" double-quote