How should 2 elements of an array be combined in PHP?

I want to combine 2 elements in an array in PHP, how can I do this. Please tell me please.

$arr = array('Hello','World!','Beautiful','Day!'); // these is my input //i want output like array('Hello World!','Beautiful Day!'); 
+5
source share
6 answers

The general solution would look something like this:

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

It combines words in pairs, therefore 1st, 2nd, 3rd and 4th, etc.

+12
source

In this case, it will 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]; } } 
+2
source

If your array is not tied 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

+1
source

Assuming you donโ€™t know the total number of elements, but know that they will always be an even number (otherwise you wonโ€™t be able to join the last element), you can simply iterate over $arr with step 2:

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

There he 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); 
+1
source

A simple solution:

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

Source: https://habr.com/ru/post/1206714/


All Articles