Saturday, April 29, 2017

Difference betwwen Single quotes vs Double quotes in PHP

Strings with double quotes

You can insert variables directly within the text of the string. The PHP parser will automatically detect such variables, convert their values into readable text, and place them in their proper places (this is called concatenating, funny word).  
<?php
 $name = "Peter";
 $age = 42
 echo "Hi, my name is $name and I am $age years old.";
?> 
Output : Hi, my name is Peter and I am 42 years old.

Strings with single quotes

The text appears as it is. When it comes to enclosing strings in PHP, single quotes are much stricter than double quotes. When you enclose a string with single quotes, PHP ignores all your variables. Plus, you are able to write double quotes inside the text without the need of the escape slash.

<?php
 $name = 'David';
 echo 'Hi, my name is $name "The Crazy" Jones.';
?>
 Output : Hi, my name is $name "The Crazy" Jones.

double quotes VS single quotes 

<?php
$s = "dollars";
echo 'This costs a lot of $s.'; // This costs a lot of $s.
echo "This costs a lot of $s."; // This costs a lot of dollars.
?>



 

No comments:

Post a Comment