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!');
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.
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]; } }
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
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:
$arr
$count = count($arr); $out=[]; for($i=0; $i<$count; $i+=2;){ $out[] = $arr[$i] . ' ' .$arr[$i+1]; } var_dump($out);
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);
A simple solution:
$new_arr=array($arr[0]." ".$arr[1], $arr[2]." ".$arr[3]);
Source: https://habr.com/ru/post/1206714/More articles:How to scale on a high DPI image of a Windows Form button? - dpiUsing REST to retrieve SharePoint view items - restNavigation Box: Gmail vs AppCompatv7 v21 - androidhadaop datanode not starting - installError using NSWindowController - objective-cGeneric STLish contains () - c ++Ability to take a snapshot of an AWS EMR cluster or name - amazon-web-servicesNode size proportional to the number of children in D3 - javascriptFree SKMap (Skobbler) memory in iOS app - iosLaravel model binding model with binding - phpAll Articles