In this chapter, you will learn about PHP String, differences between single and double quotes, PHP escape sequences, and PHP concatenation.
- PHP String Data Type
- Escape Sequences
PHP String Data Type
A string is a sequence of characters that are inside single or double quotes.
String Example –
<?php echo "a string - inside the Double quotes"; echo "<br>";//line breaker echo 'a string - inside the single quotes'; ?>
a string – inside the single quotes
You can assign strings in variables –
<?php $x = "Hello John"; $y = 'Hi Jane'; echo $x; echo "<br>"; echo $y; ?>
Difference between PHP Single quotes and Double quotes
PHP single quotes can’t parse variables data but double quotes can, for that PHP Variable Interpolation only works with double quotes.
<?php $first_name = "John"; $last_name = "Doe"; $full_name = "$first_name $last_name"; echo "$fullname"; echo "<br>";// line breaker echo '$full_name'; ?>
In single quotes, only two escape sequences work and they are –
But, all Escape Sequences works with double quotes.
Example is below –
PHP Escape Sequences
Escape sequences are used to escape a character, during the string parsing, and It is also used to give special meaning to represent line breaks, tabs, etc.
\ Backslash is used to escape.
In the above, we have already discussed that you can only escape single quotes and backslash inside the single quotes. Here’s an example –
<?php //using a backslash to escaping a single quote echo 'Hi I\'m John Doe'; echo '<br>'; //using a backslash to escaping a backslash echo '\\ this is a backslash'; echo '<br>'; echo 'Hi I\\\'m John Doe'; ?>
\ this is a backslash
Hi I\’m John Doe
And we have also discussed that all escape sequences work with double quotes. Here’s an example –
<?php echo "\"Double Quotes\""; echo "<pre>\$dollar sign \nThis is new line \n\tA new line with tab Space</pre>"; ?>
$dollar sign This is new line A new line with tab Space
Checkout – the list of Escaped characters
You can Join two string together using PHP Concatenation or string operators.
In PHP, there are two string operators –
- First is the concatenation operator
- Second is the concatenating assignment operator
Concatenation operator Example –
This operator returns the concatenation of its right and left arguments.
<?php $x = "John"; $y = "Doe"; $z = $x.$y; echo "Hello "."world"; echo "<br>";//line breaker echo $x." Doe"; echo "<br>";//line breaker echo $x.$y; echo "<br>";//line breaker // adding space echo $x." ".$y; echo "<br>";//line breaker echo $z; ?>
Concatenating assignment operator Example –
This assignment operator appends the argument on the right side to the argument on the left side.
<?php $x = "John"; $y = " Doe"; $x .= $y; echo $x; ?>
Previous is – PHP echo, print, echo VS print, Variable Interpolation