Single quotes (') and double quotes (") in PHP serve the same primary purpose of creating strings, but they behave differently when it comes to variable interpolation and escape sequences.
Single quotes treat everything inside them literally, with only two exceptions:
$name = "John"; echo 'Hello $name'; // Output: Hello $name echo 'I\'m learning PHP'; // Output: I'm learning PHP
Double quotes process several escape sequences and, most importantly, parse variables and expressions inside the string:
$name = "John"; echo "Hello $name"; // Output: Hello John echo "Array value: {$array['key']}"; // Complex expressions need curly braces
Let's examine the performance difference with some benchmarks:
$name = "John"; $iterations = 1000000; // Test single quotes $start = microtime(true); for ($i = 0; $i < $iterations; $i++) { $string = 'Hello ' . $name; } $single_quote_time = microtime(true) - $start; // Test double quotes $start = microtime(true); for ($i = 0; $i < $iterations; $i++) { $string = "Hello $name"; } $double_quote_time = microtime(true) - $start; printf("Single quotes: %.6f seconds\n", $single_quote_time); printf("Double quotes: %.6f seconds\n", $double_quote_time);
When you run this code, you'll typically find that the difference is minimal in modern PHP versions. However, there are some considerations:
$sql = 'SELECT * FROM users WHERE status = "active"'; $html = '<div> <ol> <li>Use double quotes when: <ul> <li>You need variable interpolation</li> <li>You need escape sequences like \n, \t, etc. </li> </ul> </li> </ol> <pre class="brush:php;toolbar:false">$message = "Dear $userName,\nThank you for your order #$orderId";
Here's a more complex example showing the difference in behavior:
$user = [ 'name' => 'John', 'age' => 30 ]; // Single quotes require concatenation $message1 = 'User ' . $user['name'] . ' is ' . $user['age'] . ' years old'; // Double quotes allow direct interpolation with curly braces $message2 = "User {$user['name']} is {$user['age']} years old"; // Both produce the same output: // User John is 30 years old
The above is the detailed content of Single Quotes and Double Quotes : String Interpolation and Performance. For more information, please follow other related articles on the PHP Chinese website!