0
0
PHPprogramming~5 mins

String type (single vs double quotes) in PHP

Choose your learning style9 modes available
Introduction

Strings hold text in programs. PHP lets you write strings with single or double quotes. They work a bit differently, so knowing when to use each helps you write clearer code.

When you want to write simple text without variables inside.
When you want to include variables inside the text and have them replaced with their values.
When you want to include special characters like new lines or tabs easily.
When you want to avoid extra work escaping quotes inside your string.
When you want to write code that is easy to read and understand.
Syntax
PHP
$single_quoted = 'Hello, world!';
$double_quoted = "Hello, world!";

Single quotes treat the text mostly as plain text.

Double quotes allow variables and special characters like \n (new line) to work inside the string.

Examples
In $greeting1, the variable $name is not replaced because single quotes treat it as plain text.<br>In $greeting2, the variable $name is replaced with its value because double quotes allow variable parsing.
PHP
$name = 'Alice';
$greeting1 = 'Hello, $name!';
$greeting2 = "Hello, $name!";
In $text1, the \n is shown as two characters \ and n.<br>In $text2, the \n creates a new line.
PHP
$text1 = 'Line1\nLine2';
$text2 = "Line1\nLine2";
Single quotes need backslash to escape single quote inside.<br>Double quotes need backslash to escape double quotes inside.
PHP
$quote1 = 'It\'s easy!';
$quote2 = "She said, \"Hello!\"";
Sample Program

This program shows how single and double quotes handle variables and new lines differently.

PHP
<?php
$name = "Bob";

// Using single quotes
echo 'Hello, $name!\n';

// Using double quotes
echo "Hello, $name!\n";

// Showing new lines
echo 'First line\nSecond line\n';
echo "First line\nSecond line\n";
?>
OutputSuccess
Important Notes

Use single quotes when you want the string exactly as you type it, without variable replacement.

Use double quotes when you want variables inside the string to be replaced with their values.

Remember to escape quotes inside strings if they match the surrounding quotes.

Summary

Single quotes treat the string as plain text.

Double quotes allow variables and special characters like new lines.

Choose quotes based on whether you want variable replacement or not.