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