PHP String Concatenation

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;
?>

Try It Now

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;
?>

Try It Now

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;
?>

Try It Now

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! ๐Ÿ”ฅ";
?>

Try It Now

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
?>

Try It Now

Output: I am 25 years old.


๐ŸŽฏ Key Takeaways

  • Use . to concatenate strings.
  • Use .= to append 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? ๐Ÿฑ๐Ÿถ