Imagine youโre a matchmaker
โbut instead of people, you bring strings
together! ๐
In PHP, we use the dot ( . ) operator
to merge strings. It’s like glue but without the mess! ๐งโ๐ฌ
๐น How to Concatenate Strings in PHP
To combine two or more strings, use the dot operator ( . )
:
<?php $first = "Hello"; $second = "World!"; $result = $first . " " . $second; // Adding space between words echo $result; ?>
Output: Hello World!
๐ Example 1: Concatenation with Variables
Meet Mr. Bond, James Bond
. Letโs introduce him properly! ๐ถ๏ธ
<?php $firstName = "James"; $lastName = "Bond"; $intro = "My name is " . $lastName . ", " . $firstName . " " . $lastName . "."; echo $intro; ?>
Output: My name is Bond, James Bond.
๐ Example 2: Concatenation with Assignment Operator
Use .=
to keep adding text to a variable (like a never-ending pizza ๐
).
<?php $sentence = "I love"; $sentence .= " PHP"; // Adds " PHP" to "I love" $sentence .= " so much!"; // Adds " so much!" to previous value echo $sentence; ?>
Output: I love PHP so much!
๐ Example 3: Concatenation Inside Echo
Who needs variables when you can concatenate directly inside an echo
?
<?php echo "I am " . "the concatenation master! ๐ฅ"; ?>
Output: I am the concatenation master! ๐ฅ
๐ Example 4: Number + String (Be Careful! ๐จ)
PHP automatically converts numbers to strings when concatenating. Watch out! ๐ง
<?php $age = 25; echo "I am " . $age . " years old."; // Works fine ?>
Output: I am 25 years old.
๐ฏ Key Takeaways
- Use
.
toconcatenate
strings. - Use
.=
toappend
to a string. - PHP
automatically converts numbers
when concatenating. - You can concatenate
directly inside echo statements
.
๐ Practice Time!
Try making funny sentences using string concatenation! Maybe a conversation between a cat
and a dog
? ๐ฑ๐ถ