How to combine strings together in PHP
To combine strings together, use the concatenation.
In PHP, you can do this with .
(dot).
Example 1:
<?php
$var = 'Hello';
$result = $var . ' World!';
echo $result;
?>
Output: Hello World!
Example 2:
<?php
$start = 'My name is';
$name = 'Steve';
$result = $start . ' ' . $name;
echo $result;
?>
Output: My name is Steve.
Example 3:
<?php
$array = ['red', 'green', 'blue'];
$result = 'My favorite color is ' . $array[2] . ', but I like ' . $array[0] . ' as well.';
echo $result;
?>
Output: My favorite color is blue, but I like red as well.
Alternatively, you can also extend the string saved in the specific variable with .=
.
Example:
<?php
$hello = 'Hello';
$hello .= ', Michael';
echo $hello;
?>
Output: Hello, Michael