php

Type of string in php

A lot of people wondering that the PHP has string types?. Well, The answer is Yes. Php has 4 type of string. each of those string types and different syntax and different behaviour as well. So, Let us gone through each type in details.
PHP has 4 types of string.

  • Single Quotes (Literal string)
  • Double Quotes
  • Nowdocs syntax
  • Heredocs syntax

Single Quotes

As implies that the string is enclosed in the single quotes.

For eg: $msg =  ‘The string enclosed with single quotes’;  //Output will be My string enclosed in single quotes.

Here those array of characters is displayed on it. Let us look at the 2nd example.

<?php

$string_type = ‘Double quotes’;

echo ‘The string enclosed with $string_type \n’;  //Will the output as The string enclosed with $string_type.

?>

It just displays the string as it is. Instead of parsing the variable /special characters and display the right answer. But, the It can be achieved by using the string concatenation as shown below.

<?php

$string_type = ‘Double quotes’;

echo ‘ The string enclosed with ‘.  $string_type;  //Will the output as The string enclosed with Double quotes

?>

So to be pre any string enclosed with the single quotes with display the string as it is.

Double Quotes

The string will be enclosed with the double quotes. The Most important feature of using double quotes is that it can parse the variable / special characters and display the right value. Let us take look at example 2 of single quotes and see how it behaves.

<?php

$string_type = ‘Double quotes’;

echo “The string enclosed with $string_type”;  //Will the output as The string enclosed with Double quotes

?>

There is no need for the string concatenation here. because of the nature of the double quotes behaviour.

Nowdocs syntax

Nowdocs syntax is enclosing the string with different syntax. It begins with <<< followed by the some non-keyword constant enclosed with single quotes and ends with same constant. Its behaviour is same single quotes and the only advantage is to use it in the multiple lines of the string without concatenating it.

Heredocs syntax

Heredocs syntax is almost as same as Nowdocs format. But the only difference is that variable followed by the <<< is not enclosed in single quotes. So, It begins with <<< followed by some non-keyword constant and ends with same constant, Most importantly there shouldn’t be any space before the ending variable. It behaves as same as double quotes and the only advantage is that, to use of multiple lines of the string without concatenating it.

Leave a Comment

Your email address will not be published. Required fields are marked *