PHP Strings

Defining Strings

<?php

# A string in PHP is a group of characters enclosed in single or double quotes.
$first_name = 'Glenn';
$last_name = "Quagmire";
$br = '<br>';

echo $first_name;
echo $br;
echo $last_name;

?>

Browser Output

Glenn
Quagmire

Embedding variables & special characters

<?php

$first_name = 'Stewie';

# Double quotes are required if a string includes variables or special characters.
echo "$first_name Griffin";

?>

Browser Output

Stewie Griffin

Combining Strings

<?php

$first_name = 'Glenn';
$last_name = 'Quagmire';

# Use a 'period' or 'full stop' symbol to concatenate.
$full_name = $first_name . $last_name;
echo $full_name;
echo '<br>';

# Variables and characters including single spaces can be concatenated.
$full_name = $first_name . ' ' . $last_name;
echo $full_name;
echo '<br>';

# No concatenation is needed when double quotes are used.
echo "$first_name $last_name";
echo '<br>';

# Text and variables can be combined in the output with single or double quotes and periods.
echo '<h2>' . $full_name . " says giggity giggity" . '</h2>';

# Double quotes allow a simpler method to achieve the above.
echo "<h2>$full_name says giggity giggity</h2>";

?>

Browser Output

GlennQuagmire
Glenn Quagmire
Glenn Quagmire

Glenn Quagmire says giggity giggity

Glenn Quagmire says giggity giggity