How can you merge first and last names in an associative array in PHP?
To merge first and last names in an associative array in PHP, you can loop through the array and concatenate the 'first_name' and 'last_name' values into a new 'full_name' key. This can be achieved by creating a new key in the array and assigning the concatenated value to it.
<?php
// Sample associative array with first and last names
$users = [
['first_name' => 'John', 'last_name' => 'Doe'],
['first_name' => 'Jane', 'last_name' => 'Smith'],
['first_name' => 'Alice', 'last_name' => 'Johnson']
];
// Merge first and last names into a new 'full_name' key
foreach ($users as $key => $user) {
$users[$key]['full_name'] = $user['first_name'] . ' ' . $user['last_name'];
}
// Output the modified array
print_r($users);
?>
Keywords
Related Questions
- What are the best practices for handling file uploads in PHP, especially when it comes to security measures like file type validation?
- What are the best practices for storing image files in a database versus in a directory on the server in PHP applications?
- What are the best practices for displaying and editing session variables in PHP?