Ask Your Question
4

What is the method of incorporating arrays into another array using PHP?

asked 2023-05-18 17:10:38 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-18 17:34:01 +0000

ladyg gravatar image

The method of incorporating arrays into another array using PHP is by using the array_merge() function. This function takes two or more arrays as arguments and returns a new array with all the elements from the input arrays. Here's an example:

$array1 = array('apple', 'banana');
$array2 = array('orange', 'grape');
$array3 = array('pear', 'kiwi');

$newArray = array_merge($array1, $array2, $array3);

print_r($newArray);

Output:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => grape
    [4] => pear
    [5] => kiwi
)

In this example, we have three arrays ($array1, $array2, and $array3) that we want to merge into a new array. We use the arraymerge() function to create $newArray, which contains all the elements from the three input arrays. We then use the printr() function to print the contents of the new array to the screen.

Another method to merge two arrays is to use the "+" operator:

$array1 = array('apple', 'banana');
$array2 = array('orange', 'grape');

$newArray = $array1 + $array2;

print_r($newArray);

Output:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => grape
)

In this example, we use the "+" operator to merge the $array1 and $array2 arrays into a new array, $newArray. Note that if the arrays have duplicate keys, the values from the left-hand array will be used.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-18 17:10:38 +0000

Seen: 13 times

Last updated: May 18 '23