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.
Related
I need to fill series of numbers where dash or comma is in use.
I'm using this code that works fine but when numbers starts with zero it's not working (the leading zero drop)
$str = str_replace(' ', '', '11-17,19,041244-041250);
$arr = explode(',', $str);
foreach ($arr as $elem) {
$values = explode('-',$elem);
if (count($values) != 1) {
for($i = $values[0]; $i <= $values[1]; $i++) {
$newArr[]=$i;
}
} else {
$newArr[] = $elem;
}
print_r($newArr);
}
Any help will be appreciated
Try this. Taken from here: Incrementing numbers starting from 0000 in php
<?php
$str = str_replace(' ', '', '11-17,19,041244-041250');
$arr = explode(',', $str);
foreach ($arr as $elem) {
$values = explode('-',$elem);
if (count($values) != 1) {
for($i = $values[0]; $i <= $values[1]; $i++) {
//$newArr[]=$values[0]++;
$newArr[] = str_pad($i + 1, strlen($values[0]), 0, STR_PAD_LEFT);
}
} else {
$newArr[] = $elem;
}
print_r($newArr);
}
This line:
for($i=$values[0];$i<=$values[1];$i++) $newArr[]=$i;
Is the reason this is happening. What you are doing wrong is feeding the initial loop value as a string. You can cast it to an integer and it should fix your problem.
i.e:
for($i=(int)$values[0];$i<=(int)$values[1];$i++) $newArr[]=$i;
Another approach you could consider would be:
$newArr = array_merge($newArr, range((int)$values[0],(int)$values[1]));
Just make sure to initiate $newArr = []; prior to using that method.
Look into: http://php.net/manual/en/function.range.php
<?php
$str = str_replace(' ', '', '11-17,19,041244-041250');
$arr = explode(',', $str);
foreach ($arr as $elem) {
$values = explode('-',$elem);
if (count($values) != 1) {
$newArr[] = $values[0];
for($i = $values[0]; $i < $values[1]; $i++) {
$newArr[] = str_pad($i + 1, strlen($values[0]), 0, STR_PAD_LEFT);
}
}else{
$newArr[] = $elem;
}
}
print_r($newArr);
}
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]);
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
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 ', '
Question
Currently My output is coming like this PNL testing 1,10,PNL testing 2,55, I want to manipulate it and store it in two different variables as a string like:
$teams = "PNL testing 1, PNL testing 2";
$amount = "10, 55";
Please let me know how should I split in the above format.
Code
while ($row1 = mysql_fetch_assoc($result)){
$profit = 0;
$total = 0;
$loss = 0;
$final_array = '';
$final_array .= $teams = $row1['t_name'].",";
$teams = explode(",", $teams);
$transact_money = $row1['pnl_amount'];
$pnl_results = $row1['pnl'];
$transact_money = explode("|", $transact_money);
$pnl_results = explode("|", $pnl_results);
for($i=0; $i<count($transact_money); $i++){
if($pnl_results[$i]=='Profit'){
$profit = $profit + $transact_money[$i];
}else{
$loss = $loss + $transact_money[$i];
}//end if
}//end for..
$team_profits = $profit - $loss.",";
$final_array .= $team_profits;
echo $final_array;
}
$s = "PNL testing 1,10,PNL testing 2,55";
$res = array();
$result = preg_match_all("{([\w\s\d]+),(\d+)}", $s, $res);
$teams = join(', ', $res[1]); //will be "PNL testing 1, PNL testing 2"
$amount = join(', ', $res[2]); //will be "10, 55"
$string = "PNL testing 1,10,PNL testing 2,55,";
preg_match_all("/(PNL testing \d+),(\d+),/", $string, $result);
$teams = implode(",", $result[1]);
$amount = implode(",", $result[2]);
Less fancy than RegExp, but more obvious:
$final_array = "PNL testing 1,10,PNL testing 2,55";
$final_array_array = explode(',', $final_array);
$teams = array();
$amount = array();
$index = 0;
foreach ($final_array_array as $item) {
switch ($index) {
case 0:
$teams[] = $item;
break;
case 1:
$amount[] = $item;
}
$index = 1-$index;
}