Concatenation
In PHP, you can concatenate strings using the dot operator (.). Here's a detailed explanation and some examples:
Basic Concatenation
<?php
$firstName = "John";
$lastName = "Doe";
// Concatenate first and last names
$fullName = $firstName . " " . $lastName;
echo $fullName; // Outputs "John Doe"
?>
Concatenation with Assignment
You can use the .= operator to append a string to an existing variable.
<?php
$greeting = "Hello";
$greeting .= " ";
$greeting .= "World!";
echo $greeting; // Outputs "Hello World!"
?>
Concatenation within Echo or Print
You can directly concatenate strings within an echo or print statement.
<?php
$city = "New York";
$state = "NY";
echo "I live in " . $city . ", " . $state . "."; // Outputs "I live in New York, NY."
?>
Concatenation in Function Calls
You can concatenate strings when passing them as arguments to functions.
<?php
function welcomeMessage($name) {
return "Welcome, " . $name . "!";
}
echo welcomeMessage("Alice"); // Outputs "Welcome, Alice!"
?>
Concatenation with Variables and Literals
You can mix variables and literals in concatenation.
<?php
$day = "Monday";
$activity = "coding";
$sentence = "On " . $day . "s, I enjoy " . $activity . ".";
echo $sentence; // Outputs "On Mondays, I enjoy coding."
?>
Concatenation in Loops
You can use concatenation within loops to build strings dynamically.
<?php
$items = array("apple", "banana", "cherry");
$list = "";
foreach ($items as $item) {
$list .= $item . ", ";
}
// Remove the trailing comma and space
$list = rtrim($list, ", ");
echo $list; // Outputs "apple, banana, cherry"
?>
Concatenation with HTML
You can concatenate strings to create HTML content.
<?php
$title = "PHP Concatenation";
$body = "This is a simple example.";
$html = "<html><head><title>" . $title . "</title></head>";
$html .= "<body><p>" . $body . "</p></body></html>";
echo $html;
?>
Example with Variables and HTML
Combining variables with HTML for dynamic content:
<?php
$name = "John";
$age = 30;
echo "<div>Name: " . $name . "</div>";
echo "<div>Age: " . $age . "</div>";
?>