0

I have the two PHP loops as below:

foreach ($directData as $key => $val) {
            echo $val;
            echo "|"; //Just for the visual.
}

foreach ($sdata as $key => $val) {
            echo $val;
            echo "|"; //Just for the visual.
}

Which output:

5|5|5|10|10|10|0| and the second: 2|2|2|5|5|5|20|

My question is, how can I combine these two result (add them) and print it out like above?

So, it would be:

7|7|7|15|15|15|20
1
  • do arrays have the same keys? Commented Sep 6, 2015 at 10:32

5 Answers 5

1
php > $a = [1, 2, 3];
php > $b = [4, 5, 6];
php > $c = array_map(function($x, $y){ return $x + $y; }, $a, $b);
php > print_r($c);
Array
(
    [0] => 5
    [1] => 7
    [2] => 9
)
php > print_r(implode($c, '|') . '|');
5|7|9|
Sign up to request clarification or add additional context in comments.

Comments

0

Broken down for better readability, this will sum them into $new array.

array_map will iterate through both given arrays and apply the callback function to both of the arrays at their current indexes. The callback function will sum the values of at current indexes.

$new=array_map(
    function(){
        return array_sum(func_get_args());
    },
    $directData, $sdata
);

$out= '';
foreach ($new as $key => $val)
    $out .= $val.'|';
echo rtrim($out,'|');

1 Comment

Ty for spotting it, fixed.
0

in simple way you can do it like:

$finalData = array_map(function () {
    return array_sum(func_get_args());
}, $directData, $sdata );
print_r($finalData );

Comments

0

If each index corresponds in the arrays

   $rezult = array();   

   for($i=0;$i<count($directData);$i++){
      $rezult[] = $directData[$i] + $sdata[$i];
   }

   echo join("|",$rezult);

Comments

0

Here is a method that uses the iterators that all PHP arrays have.

/**
 * Use the iterator that all PHP arrays have.
 *
 * Check both arrays for having entries.
 */

$listOut = array(); // output in here

while (current($listA) !== false && current($listB) !== false) {
    $listOut[] = current($listA) + current($listB);
    next($listA);
    next($listB);
}

Input:

$listA = array(5, 5, 5, 10, 10, 10, 0);
$listB = array(2, 2, 2, 5, 5, 5, 20, );

Output

Array
(
    [0] => 7
    [1] => 7
    [2] => 7
    [3] => 15
    [4] => 15
    [5] => 15
    [6] => 20
)

7| 7| 7| 15| 15| 15| 20

1 Comment

add for completeness of ways of processing arays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.