PHP - String in single quotes vs double quotes

Introduction

We can enclose the strings within single quotes, but we can also enclose them within double quotes.

Within single quotes, a string is exactly as it is represented.

Within double quotes, some rules are applied before showing the final result.

Double quotes supports escape characters and variable expansions.

Escape characters are special characters than cannot be represented easily. For example, new lines or tabs.

To represent them, we use escape sequences, which are the concatenation of a backslash \ followed by some other character.

For example, \n represents a new line, and \t represents a tabulation.

Variable expanding can include variable references inside the string, and PHP replaces them by their current value.

Demo

<?php
     $firstname = 'Jason'; 
     $surname = 'Smith'; 
     echo "My name is $firstname $surname.\nI am a master of time and space. \"hi!\""; 
?>//w ww  .  j a v a2  s. c  o  m

Result

Here, \n inserted a new line.

\" added the double quotes, and the variables $firstname and $surname were replaced by their values.

Related Topics