Gunjan Patel
Gunjan Patel

Reputation: 2372

How should merge 2 element of array in 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!');

Upvotes: 5

Views: 117

Answers (6)

Tibor B.
Tibor B.

Reputation: 1690

Here it is:

$arr = array('Hello', 'World!', 'Beautiful', 'Day!');
$result = array();
foreach ($arr as $key => $value) {
  if (($key % 2 == 0) && (isset($arr[$key + 1]))) {
    $result[] = $value . " " . $arr[$key + 1];
  }
}
print_r($result);

Upvotes: 1

Paul
Paul

Reputation: 9022

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];
    }
}

Upvotes: 2

Steve
Steve

Reputation: 20469

Presuming you dont know the total number of elements, but do know they will always an even number (else you cant join the last element), you can simply iterate $arr in steps of 2:

$count = count($arr);
$out=[];
for($i=0; $i<$count; $i+=2;){
    $out[] = $arr[$i] . ' ' .$arr[$i+1];
}
var_dump($out);

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173572

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.

Upvotes: 12

dynamic
dynamic

Reputation: 48111

In case your array is not fixed to 4 elements

$arr = array();
$i = 0;
foreach($array as $v){
  if (($i++) % 2==0)
    $arr[]=$v.' ';
  else {
    $arr[count($arr)-1].=$v;
  }
}

Live: http://ideone.com/VUixMS

Upvotes: 1

Serpes
Serpes

Reputation: 672

A easy solution would be:

$new_arr=array($arr[0]." ".$arr[1], $arr[2]." ".$arr[3]);

Upvotes: 0

Related Questions