Combining variables
Learn to combine two variables and assign the result to a new variable.
Combining variables: .
To combine two variables or values, use the dot . operator. This is called concatenation.
Example: $firstName = "Alex"; and $lastName = "Smith";. echo $firstName . $lastName; prints AlexSmith.
To add a space between them, concatenate a space string: echo $firstName . " " . $lastName; prints Alex Smith.
Each piece stays on the same line; echo produces a single output.
Arithmetic with number variables
With number variables you can add, subtract, multiply and divide: +, -, *, /.
Example: $price = 100; and $tax = 20;. $total = $price + $tax; makes $total hold 120.
For multiplication use $price * 2;, for division use $price / 4;. You assign the result to a new variable and print it with echo.
PHP computes the result automatically; you only need to assign and print it.
Exercise Combine first and last name
Assign "Alex" to $firstName and "Smith" to $lastName. Combine them with . to print Alex Smith; put a space between. End the line with \n.
Show example solution
Write echo $firstName . " " . $lastName . "\n";.
Example solution:
<?php
$firstName = "Alex";
$lastName = "Smith";
echo $firstName . " " . $lastName . "\n";
Test yourself
-
What does $a = "Hello "; $b = "World"; echo $a . $b; print?
$a = "Hello "; $b = "World"; echo $a . $b;- Hello
- World
- Hello World
- HelloWorld
Show answer
Hello World — Correct! . concatenates; "Hello " + "World" = "Hello World".
-
Add the concatenation operator
echo $firstName ____ $lastName;Show answer
echo $firstName . $lastName; -
Match each operator to its meaning
- .
- concatenates
- +
- adds
- -
- subtracts
- ++
- increases by one