How to Concatenate First and Last Name into One String in PHP?

In PHP, you can combine (concatenate) the first name and last name into a single string using the `.` (dot) operator or `sprintf()`.

Method 1: Using the `.` (Dot) Operator

<?php
$first_name = "John";
$last_name = "Doe";
$full_name = $first_name . " " . $last_name; // Concatenation with space
echo $full_name; // Output: John Doe
?>

Explanation:

The `.` operator joins the two strings together.
A `” “` (space) is added between the names.

Method 2: Using `sprintf()` (Formatted String)

<?php
$first_name = "Jane";
$last_name = "Smith";
$full_name = sprintf("%s %s", $first_name, $last_name);
echo $full_name; // Output: Jane Smith
?>

Method 3: Using `implode()` (Array to String)

<?php
$first_name = "Alice";
$last_name = "Brown";
$full_name = implode(" ", [$first_name, $last_name]);
echo $full_name; // Output: Alice Brown
?>

Why use `implode()`?

– Great when handling dynamic data with multiple values.
– Can be used to join more than two strings.

Method 4: Using `join()` (Alias of `implode()`)

<?php
$first_name = "Michael";
$last_name = "Johnson";
$full_name = join(" ", [$first_name, $last_name]);
echo $full_name; // Output: Michael Johnson
?>

`join()` is simply an alias of `implode()`, so it works the same way.

Method 5: Using `str_replace()` to Handle Extra Spaces

If you have dynamic user input, extra spaces may appear. You can clean them up using `trim()`:

<?php
$first_name = " Robert ";
$last_name = " Williams ";
$full_name = trim($first_name) . " " . trim($last_name);
echo $full_name; // Output: Robert Williams
?>

Why use `trim()`?

Removes unwanted spaces before and after the name.