In this chapter, you will learn about PHP String, differences between single and double quotes, PHP escape sequences, and PHP concatenation.
A string is a sequence of characters that are inside single or double-quotes.
<?php echo "a string - inside the Double quotes"; echo "<br>";//line breaker echo 'a string - inside the single quotes'; ?>
<?php $x = "Hello John"; $y = 'Hi Jane'; echo $x; echo "<br>"; echo $y; ?>
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.
An example is below –
हिंदी | PHP Escape Sequences in Hindi
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.
\ The 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'; ?>
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
Check out – the list of Escaped characters
Concatenation in PHP
हिंदी | PHP Concatenation in Hindi
You can Join two string together using PHP Concatenation or string operators.
In PHP, there are two string operators –
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; ?>