String Concatenation
Part of the Fundamentals section of Coddy's PHP journey — lesson 12 of 71.
String concatenation is the process of joining two or more strings to create a single, longer string.
Use the dot operator (.) to concatenate strings. This operator takes the strings on its left and right sides and combines them into one continuous string:
$firstName = "John";
$lastName = "Smith";
$fullName = $firstName . $lastName;
echo $fullName; // Outputs: JohnSmithNotice that concatenation doesn't automatically add spaces between strings. If you want spaces or other characters between your strings, you need to include them explicitly:
$fullName = $firstName . " " . $lastName;
echo $fullName; // Outputs: John SmithChallenge
EasyYou are provided with a first name and a last name variables.
Create two string variables using concatenation:
$fullName- concatenate first name, a space, and last name$greeting- concatenateHello,with the full name
Cheat sheet
String concatenation joins two or more strings together using the dot operator (.):
$firstName = "John";
$lastName = "Smith";
$fullName = $firstName . $lastName;
echo $fullName; // Outputs: JohnSmithConcatenation doesn't add spaces automatically. Include them explicitly:
$fullName = $firstName . " " . $lastName;
echo $fullName; // Outputs: John SmithTry it yourself
<?php
$firstName = "Jhon";
$lastName = "Smith";
// Write your code below
$fullName = ?;
$greeting = ?;
echo $fullName . "\n";
echo $greeting . "\n";
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types5Conditional Logic
If StatementIf - ElseThe Ternary OperatorNull Coalescing OperatorSwitch StatementRecap - Making Decisions3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators