PHP Strings
Strings in PHP are sequences of characters, such as words or sentences. They can be enclosed in single quotes or double quotes.
Example of PHP Strings
<?php
$string1 = 'Hello, World!';
$string2 = "Hello, World!";
$string3 = 'This is a single-quoted string.';
$string4 = "This is a double-quoted string.";
echo $string1 . "\n";
// Outputs: Hello, World!
echo $string2 . "\n";
// Outputs: Hello, World!
echo $string3 . "\n";
// Outputs: This is a single-quoted string.
echo $string4 . "\n";
// Outputs: This is a double-quoted string.
?>
Output:
Hello, World!
Hello, World!
This is a single-quoted string.
This is a double-quoted string.
Explanation: This example demonstrates the use of single quotes and double quotes to enclose strings in PHP. The echo
statement is used to output the strings.
Example of PHP Strings with Variables
<?php
$name = 'John';
$age = 30;
$string = 'My name is $name and I am $age years old.';
echo $string . "\n";
// Outputs: My name is $name and I am $age years old.
$string = "My name is $name and I am $age years old.";
echo $string . "\n";
// Outputs: My name is John and I am 30 years old.
?>
Output:
My name is $name and I am $age years old.
My name is John and I am 30 years old.
Explanation: This example demonstrates the use of variables within strings in PHP. When using single quotes, the variables are not parsed, but when using double quotes, the variables are replaced with their values.