PHP
Summary - String basics
Build a greeting message combining string creation, concatenation and interpolation.
String basics recap
In this group you learned to create strings, count length with strlen(), join with . and .=, interpolate variables in double quotes, and use escape sequences like \n.
Single quotes are ideal for fixed text; double quotes work for both variable values and escape sequences. With these tools you can build real messages: greetings, product info, order summaries. Now two tasks await that combine these skills.
Exercise Print the greeting and its length
Assign "Alex" to $name. Assign "Hello, $name!" to $msg using double quotes (use variable interpolation). Then in a single echo join $msg, "\n" and strlen($msg) with the . operator: echo $msg . "\n" . strlen($msg);
Show example solution
First assign $name and $msg, then echo $msg . "\n" . strlen($msg);
Example solution:
<?php
$name = "Alex";
$msg = "Hello, $name!";
echo $msg . "\n" . strlen($msg);
Exercise Build a product info card
Assign "Coffee" to $product. Assign 45 (number) to $price. Assign the following to $info using double quotes: "Product: \"{$product}\"\nPrice: $price TL" (use the \" escape, {$product} curly braces and \n newline). Then print it with echo $info;.
Show example solution
Assign the two variables, then build $info with escape and braces, then echo $info;
Example solution:
<?php
$product = "Coffee";
$price = 45;
$info = "Product: \"{$product}\"\nPrice: $price TL";
echo $info;
Your string toolkit is ready
Congratulations! In this summary you combined string creation, concatenation, variable interpolation and escape sequences. Single quotes are ideal for fixed text; double quotes work for both variable values and escape sequences.
With these tools you can build real messages: greetings, product info, order summaries. These appear all the time in everyday PHP code. In the next group you will learn to convert, split and search strings.
Test yourself
-
$name = "Alex"; echo 'Hello $name'; what is the output?
$name = "Alex";
echo 'Hello $name';
- Hello Alex
- Hello $name;
- Hello $name
- It errors
Show answer
Hello $name — Correct. Single quotes do not interpolate $name; the output is "Hello $name".
-
Append a name to the greeting
$greeting = 'Welcome';
$greeting____ ', Alex!';
echo $greeting;
Show answer
$greeting = 'Welcome';
$greeting.= ', Alex!';
echo $greeting;
Next lesson: The if statement