Menu
Coddy logo textTech

String Operators

Part of the Fundamentals section of Coddy's PHP journey — lesson 22 of 71.

Just like numbers have arithmetic operators, strings have their own operators for combining text. You've already seen the concatenation operator (.) in an earlier lesson. Now let's look at its combined assignment counterpart.

The concatenation assignment operator (.=) appends text to an existing string variable, following the same pattern as += for numbers:

<?php
$message = "Hello";
$message = $message . " World"; // The long way
$message .= "!";                // The shorthand way
echo $message; // Outputs: Hello World!
?>

This operator is particularly useful when building strings piece by piece:

<?php
$greeting = "Welcome";
$greeting .= ", ";
$greeting .= "John";
$greeting .= "!";
echo $greeting; // Outputs: Welcome, John!
?>

Remember: use . to join strings together, and .= to append to an existing string variable. These are the two string operators you'll use most often in PHP.

challenge icon

Challenge

Easy

Read three strings from input: a greeting, a name, and a punctuation mark.

Create a variable called $message and initialize it with the greeting. Then use the concatenation assignment operator (.=) to:

  1. Append a space and the name to $message
  2. Append the punctuation mark to $message

Print the final message.

Example:

If the inputs are Hello, Alice, and !, the output should be:

Hello Alice!

Cheat sheet

The concatenation assignment operator (.=) appends text to an existing string variable:

<?php
$message = "Hello";
$message .= " World";  // Appends " World" to $message
$message .= "!";       // Appends "!" to $message
echo $message;         // Outputs: Hello World!
?>

This is shorthand for $message = $message . " World";

Building strings piece by piece:

<?php
$greeting = "Welcome";
$greeting .= ", ";
$greeting .= "John";
$greeting .= "!";
echo $greeting; // Outputs: Welcome, John!
?>

Try it yourself

<?php
// Read input
$greeting = trim(fgets(STDIN));
$name = trim(fgets(STDIN));
$punctuation = trim(fgets(STDIN));

// TODO: Write your code below
// Initialize $message with the greeting
// Use .= to append a space and the name
// Use .= to append the punctuation mark

// Output the result
echo $message;
?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals