Tags
Asked 3 years ago
9 Jun 2021
Views 411
angeo

angeo posted

how to combine two associative arrays into one array in php ?

how to combine two associative arrays into one array in php ?
jaman

jaman
answered Apr 26 '23 00:00

In PHP, you can combine two associative arrays into one array using the array_merge() function. This function merges the elements of two or more arrays together to create a new array.

Here's an example of how to combine two associative arrays into one array:



// Define two associative arrays
$array1 = array("name" => "John", "age" => 30, "location" => "New York");
$array2 = array("job" => "Developer", "hobby" => "Reading");

// Combine the two arrays
$result = array_merge($array1, $array2);

// Output the resulting array
print_r($result);

In this example, we define two associative arrays $array1 and $array2. We then use the array_merge() function to merge the two arrays into a new array $result. The resulting array contains all the elements from both arrays.

Output:



Array
(
    [name] => John
    [age] => 30
    [location] => New York
    [job] => Developer
    [hobby] => Reading
)

Note that if the two arrays have keys that are the same, the value from the second array will overwrite the value from the first array.
Post Answer