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

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.

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

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

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);

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);

A easy solution would be:
$new_arr=array($arr[0]." ".$arr[1], $arr[2]." ".$arr[3]);

Related

How to add string into array in PHP?

I have these for loop to determine consecutive number. What I achieve so far is to print the output in string.
$arr = [1,2,3,6,11,5,4,8,9,3];
for($start=0; $start<=count($arr); $start++){
for($end=$start+1; $end<=count($arr); $end++){
$total = $arr[$end] - $arr[$start];
if($total == 1){
echo 'Number is '.$arr[$start].','.$arr[$end].'<br/>';
} else {
echo '';
}
$arr[$start++];
}
}
My goal is to add the output into array.
I tried to use multidimensional array but no output display.
$arr = [1,2,3,6,11,5,4,8,9,3];
$arr3 = [];
for($start=0; $start<=count($arr); $start++){
for($end=$start+1; $end<=count($arr); $end++){
$total = $arr[$end] - $arr[$start];
if($total == 1){
$arr2 = array();
$arr2[] = $arr[$start].','.$arr[$end].'';
$arr3[] = $arr2;
} else {
}
$arr[$start++];
}
}
echo '<pre>';
print_r($arr3);
echo '</pre>';
exit;
Appreciate if someone can help me. Thanks.
you can simply use array functions, if sorting is important to you as #nice_dev said, you must sort your array before.
$arr = [1,2,3,6,11,5,4,8,9,3];
$cons = [] ;
while (array_key_last($arr) != key($arr)) {
if ((current($arr)+1) == next($arr)) {
prev($arr);
$cons[] = current($arr) . ',' . next($arr);
}
}
print_r($cons);
the output will be :
Array
(
[0] => 1,2
[1] => 2,3
[2] => 8,9
)
You can better sort() the input array first. This way, collecting all consecutive elements would get much simpler. If value at any index isn't +1 of the previous one, we add the $temp in our $results array and start a new $temp from this index.
Snippet:
<?php
$arr = [1,2,3,6,11,5,4,8,9,3];
$result = [];
sort($arr);
$temp = [];
for($i = 0; $i < count($arr); ++$i){
if($i > 0 && $arr[ $i ] !== $arr[$i - 1] + 1){
$result[] = implode(",", $temp);
$temp = [];
}
$temp[] = $arr[$i];
if($i === count($arr) - 1) $result[] = implode(",", $temp);
}
print_r($result);
Online Demo

get a set of values from an array

i have a set of arrays:
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
what i want to do is to get a set of $data array from each number of $nums array,
the output must be:
output:
2=11,22
3=33,44,55
1=66
what i tried so far is to slice the array and remove the sliced values from an array but i didn't get the correct output.
for ($i=0; $i < count($nums); $i++) {
$a = array_slice($data,0,$nums[$i]);
for ($x=0; $x < $nums[$i]; $x++) {
unset($data[0]);
}
}
Another alternative is to use another flavor array_splice, it basically takes the array based on the offset that you inputted. It already takes care of the unsetting part since it already removes the portion that you selected.
$out = array();
foreach ($nums as $n) {
$remove = array_splice($data, 0, $n);
$out[] = $remove;
echo $n . '=' . implode(',', $remove), "\n";
}
// since nums has 2, 3, 1, what it does is, each iteration, take 2, take 3, take 1
Sample Output
Also you could do an alternative and have no function usage at all. You'd need another loop though, just save / record the last index so that you know where to start the next num extraction:
$last = 0; // recorder
$cnt = count($data);
for ($i = 0; $i < count($nums); $i++) {
$n = $nums[$i];
echo $n . '=';
for ($h = 0; $h < $n; $h++) {
echo $data[$last] . ', ';
$last++;
}
echo "\n";
}
You can array_shift to remove the first element.
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
foreach( $nums as $num ){
$t = array();
for ( $x = $num; $x>0; $x-- ) $t[] = array_shift($data);
echo $num . " = " . implode(",",$t) . "<br />";
}
This will result to:
2 = 11,22
3 = 33,44,55
1 = 66
This is the easiest and the simplest way,
<?php
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
$startingPoint = 0;
echo "output:"."\n";
foreach($nums as $num){
$sliced_array = array_slice($data, $startingPoint, $num);
$startingPoint = $num;
echo $num."=".implode(",", $sliced_array)."\n";
}
?>

Pair the elements in an array by two's then find the difference and sum

Let's say I have this array
$number = [2,1,4,3,6,2];
First pair the elements on an array by two's and find their difference
so this is the output in the first requirement
$diff[] = [1,1,4];
Second sum all the difference
this is the final output
$sum[] = [6];
Conditions:
the array size is always even
the first element in a pair is always greater than the second one, so their is no negative difference
What I've done so far is just counting the size of an array then after that I don't know how to pair them by two's. T_T
Is this possible in php? Is there a built in function to do it?
One line:
$number = [2,1,4,3,6,2];
$total = array_sum(array_map(function ($array) {
return current($array) - next($array);
}, array_chunk($number, 2)));
echo $total;
This should work fine:
<?
$number = array(2,1,4,3,6,2);
for($i=0;$i<count($number); $i+=2){
$dif[] = $number[$i] - $number[$i+1];
}
print_r($dif);
$sum = 0;
foreach ($dif as $item){
$sum += $item;
}
echo 'SUM = '.$sum;
?>
Working CODE
If you want all the different stages kept,
$numbers = [2,1,4,3,6,2];
$diff = [];
for($i=0,$c=count($numbers);$i<$c;$i+=2)
{
$diff[] = $numbers[$i]-$numbers[$i+1];
}
$sum = array_sum($diff);
Else, to just get the total and bypass the diff array:
$numbers = [2,1,4,3,6,2];
$total = 0;
for($i=0,$c=count($numbers);$i<$c;$i+=2)
{
$total += $numbers[$i]-$numbers[$i+1];
}
I have got this far it gives the required solution.
$arr = array(2,1,4,3,6,2);
$temp = 0;
$diff = array();
foreach ($arr as $key => $value) {
if($key % 2 == 0) {
$temp = $value;
}
else {
$diff[] = $temp - $value;
}
}
print_R($diff);
print 'Total :' . array_sum($diff);
Note : Please update if any one knows any pre-defined function than can sorten this code.
Please check and see if this works for you.
<?php
$sum=0;
$number = array(2,1,4,3,6,2);
for ($i=0;$i<=count($number);$i++) {
if ($i%2 == 1 ) {
$sum = $sum + $number[$i-1] - $number[$i];
}
}
print $sum;
?>
Well with your conditions in mind I came to the following
$number = [2,1,4,3,6,2];
$total = 0;
for($i = 0; $i < count($number); $i+=2) {
$total += $number[$i] - $number[$i + 1];
}
Try this one:
$number = array(2,1,4,3,6,2);
$diff = array();
$v3 = 0;
$i=1;
foreach($number as $val){
if ($i % 2 !== 0) {
$v1 = $val;
}
if ($i % 2 === 0) {
$v2 = $val;
$diff[] = $v1-$v2;
$v3+= $v1-$v2;
}
$i++;
}
print $v3;//total value
print_r($diff); //diff value array

PHP implode() using conditional logic based on object index

Assuming a list like this:
$array = array('item1', 'item2', 'item3'); // etc...
I would like to create a comma separated list like so:
implode(',', $array);
But have the added complication that I'd like to use the following logic: if the item index is a multiple of 10, use ',<br>' instead of just ',' for the separator in the implode() function.
What's the best way to do this with PHP?
I did this like so, but wonder if there's a more concise way?
function getInventory($array, $title) {
$list = array();
$length = count($array);
$i = 1;
foreach($array as $item) {
$quantity = $item[1];
if(!$quantity)
$quantity = 1;
$item_text = $quantity . $item[3];
if($i > 9 && ($i % 10) == 0) {
$item_text .= ',<br>';
} elseif($i !== $length) {
$item_text .= ',';
}
$list[] = $item_text;
$i++;
}
$list = implode('', $list);
$inventory = $title . $list . '<br>';
return $inventory;
}
This solution will work if you want to use the <br> whenever the key is divisible by 10.
implode(',', array_map(function($v, $k){ return $k%10 ? $v : '<br>' . $v; }, $array, array_keys($array)));
If instead you want every 10th element and not just the element where the key is divisible by 10, use this:
implode(',', array_map(function($v, $k){ return $k%10 ? $v : '<br>' . $v; }, $array, range(1, count($array)));
Thanks to #Jacob for this possibility.
We keep the , for the implode function and variably adjust the input array values to be prepended with a <br>.
$k%10 uses the modulus operator to return the remainder for $k divided by 10 which will be 0 when $k is a multiple of 10.
As long as it's not the actual array keys that you're concerned about but the position in the array (ie. the break is on every tenth element rather than every index that is a multiple of ten), then you can do it this way:
$foo = array();
for($n = 0; $n < 54; $n++) $foo[] = $n;
$parts = array_chunk($foo, 10);
for($n = 0; $n < count($parts); $n++){
echo implode(',', $parts[$n]);
if($n < count($parts) - 1) echo ',';
echo "<br/>\n";
}
$str = '';
$array = ....;
$i = 0;
foreach($array as $index)
$str .= $array[$index].' ,'.($index % 10 ? ' ' : '<br/>');
$str = substr($str, 0, strlen($str) - 2); // trim the last two characters ', '

PHP separate even and odd values from an array

I'm using the below code to separate odd and even and store it in different variable. When there are only 2 value available then it works fine but when the number value increases then it doesn't. I want to make it dynamic so that n number of values can be separated and stored correctly.
Example:
If the value of
$final_array = "PNL testing 1,10,PNL testing 2,35,";
It prints nicely:
$teams = "PNL testing 1, PNL testing 2";
$amount = "10, 35";
But when it increases from
$final_array = "PNL testing 1,10,PNL testing 2,35,";
to
$final_array = "PNL testing 1,10,PNL testing 2,35,Team 3,95,";
Then also it prints
$teams = "PNL testing 1, PNL testing 2";
$amount = "10, 35";
Please guide me through on where I am going wrong.
$res = array();
$result = preg_match_all("{([\w\s\d]+),(\d+)}", $final_array, $res);
$teams = join(', ', $res[1]); //will display teams
$amount = join(', ', $res[2]); //will display amount every team have
echo $teams . "<br />" . $amount;
I think you can totally drop the REGEX in favor of good old explode/implode with some logic in it:
$teams = array();
$amount = array();
$a = explode(',', trim(trim($final_array), ','));
foreach ($a as $i => $v)
if (($i % 2) == 0) $teams[] = trim($a);
else $amount[] = trim($a);
$teams = implode(', ', $teams);
$amount = impode(', ', $amount);
In the above code $tms and $amn are temporary arrays. In the foreach we take the exploded values from the string and we store them in those two arrays sorting them by key (if it's even then it's a team otherwise it's an amount).
At the end we just implode the new values into your output variables $teams and $amount.
It will much easier I think to use explode:
$result = explode(',', $final_array);
$teams = array();
$amount = array();
foreach ($result as $key => $value) {
if ($key % 2 == 0) {
$teams[] = $value;
} else {
$amount[] = $value;
}
}
$teams = implode(', ', $teams); //will display teams
$amount = implode(', ', $amount); //will display amount every team have
echo $teams."<br />".$amount;
I would change this part of Michal Trojanowski for more efficiency
foreach ($result as $key => $value) {
if ($key % 2 == 0) {
$teams[] = $value;
} else {
$amount[] = $value;
}
}
you see it has an extra condition we can remove it by like this
$length = count($result);//cache count result
for ($i = 0; $i < $length; $i += 2) {
$teams[] = $result[$i];
}
for ($i = 1; $i < $length; $i += 2) {
$amount[] = $result[$i];
}
Here the loop is running same but it just removes the the condition.

Categories