Mark C
Mark C

Reputation: 41

How to return value of an array inside a loop and use it outside in PHP

I have a code like this: Lets assume that this arrays has this values:

$arr1 = array();
$arr2 = array();
$result = array();

$arr1[] = array( 'grade' => [1,2,3,4] );
$arr2[] = array( 'grade' => [1,2,3,4] );

foreach($arr1 as $a1){
$set1 = $a1['grade'];
    foreach($arr2 as $a2){
    $set2 = $a2['grade'];
    }
$result[] = array('show_result' => $set1+$set2);
}

foreach{$result as $res){
    echo $res['show_result'];
}

The output of the array $res['show_result'] must be:

2, 4, 6, 8

But I get the wrong addition of this arrays. Help will be much appreciated.

Upvotes: 0

Views: 222

Answers (2)

PHPnoob
PHPnoob

Reputation: 614

  1. As Joni said, your first error is on line 3: ' should be ;
  2. Then, you're not filling arrays like you wanted : array( 'grade' => 1,2,3,4 ); creates an array with first key is 'grade' with value '1', then second key is '0' with value '2' etc...
  3. Your last foreach loop has a syntax error similar to your first error.

See a working correction here

$arr1 = array();
$arr2 = array();
$result = array();

array_push($arr1, 1, 2, 3, 4); //fill array with 4 values (integers)
array_push($arr2, 1, 2, 3, 4); //fill array with 4 values (integers)

//so $arr1 & $arr2 are now a 4 elements arrays

$length = count($arr1); //size of array, here 4 

for ($i = 0; $i < $length; $i++) { //loop over arrays
    array_push($result, ($arr1[$i] + $arr2[$i])); //fill the results array with sum of the values from the same position 
}

var_dump($result);

Upvotes: 1

waterloomatt
waterloomatt

Reputation: 3742

You have quite a few syntax errors in your code.

Although this solution works, the idea behind using the same counter, $i, to extract a value from both arrays is brittle. For example, you'll get an Undefined offset if the first array has 5 grades instead of 4. If you take a step back and explain your problem in the larger context, perhaps we can provide a better solution. I get the sneaking suspicion you're asking an XY Problem.

http://sandbox.onlinephpfunctions.com/code/bb4f492c183fcde1cf4edd50de7ceebf19fe343a

<?php

$gradeList1 = ['grade' => [1,2,3,4]];
$gradeList2 = ['grade' => [1,2,3,4]];
$result = [];

for ($i = 0; $i < count($gradeList1['grade']); $i++) {

    $first = $gradeList1['grade'][$i];
    $second = $gradeList2['grade'][$i];

    $result['show_result'][] = (int)$first + (int)$second;
}

var_dump($result);

Upvotes: 1

Related Questions