Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should merge 2 element of array in PHP?

Tags:

arrays

php

I want to merge 2 element in array in PHP how can i do that. Please any on tell me.

$arr = array('Hello','World!','Beautiful','Day!');  // these is my input

//i want output like 

array('Hello World!','Beautiful Day!');
like image 880
Gunjan Patel Avatar asked Nov 12 '14 11:11

Gunjan Patel


People also ask

How do I merge two elements in an array?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

How can I merge two arrays in PHP without duplicates?

You can use the PHP array_unique() function and PHP array_merge() function together to merge two arrays into one array without duplicate values in PHP.

What is Array_keys () used for in PHP?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.


2 Answers

The generic solution would be something like this:

$result = array_map(function($pair) {
    return join(' ', $pair);
}, array_chunk($arr, 2));

It joins together words in pairs, so 1st and 2nd, 3rd and 4th, etc.

like image 72
Ja͢ck Avatar answered Oct 12 '22 12:10

Ja͢ck


Specific to that case, it'd be very simple:

$result = array($arr[0].' '.$arr[1], $arr[2].' '.$arr[3]);

A more general approach would be

$result = array();
for ($i = 0; $i < count($arr); $i += 2) {
    if (isset($arr[$i+1])) {
        $result[] = $arr[$i] . ' ' . $arr[$i+1];
    }
    else {
        $result[] = $arr[$i];
    }
}
like image 39
Paul Avatar answered Oct 12 '22 14:10

Paul