0

Creating an array and diving it in 3 other arrays with the PHP function array_chunk()

$sumArray = array ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 );
$reviews_count = 4;
$sum_divided_array = array();
$sum_divided_sub_array = array();
/* Dividing the array in 3 other arrays */
$divided_array = array_chunk($sumArray, $reviews_count); 

foreach ($divided_array as $key_divided_sub_array => $sum_divided_sub_array) { 
    for ($i = 0; $i <= (count($sum_divided_sub_array) -1); $i++) {
        if(isset($sum_divided_sub_array[$i])) {
            if(array_key_exists($i, $sum_divided_sub_array)) {
                $sum_divided_array[$i] +=  $sum_divided_sub_array[$i]; 
            }
        }                                               
    }    
}
print_r( $sum_divided_array );
  • You are trying to read-access `$sum_divided_array[$i]` without checking whether that index already exists. – 04FS Feb 25 '19 at 14:09
  • Your two ifs seem to be checking the same thing in two different ways. You probably meant to check the array $sum_divided_array in the inner one … But you still need an else branch for that, otherwise you would not be doing anything with `$sum_divided_sub_array[$i]` at all in that case. – 04FS Feb 25 '19 at 14:13
  • Possible duplicate of ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – devpro Feb 25 '19 at 14:19

1 Answers1

0

The main error is that you missed checking if $sum_divided_array[$i] exists, before adding something to it, the right code would be:

<?php
        //Enter your code here, enjoy!

$sumArray = array ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 );
$reviews_count = 4;
$sum_divided_array = array();
$sum_divided_sub_array = array();
/* Dividing the array in 3 other arrays */
$divided_array = array_chunk($sumArray, $reviews_count); 

foreach ($divided_array as $key_divided_sub_array => $sum_divided_sub_array) { 
    for ($i = 0; $i <= (count($sum_divided_sub_array) -1); $i++) {
        if(isset($sum_divided_sub_array[$i])) {
            if(isset($sum_divided_array[$i])) {
                $sum_divided_array[$i] +=  $sum_divided_sub_array[$i]; 
            } else {
                $sum_divided_array[$i] =  $sum_divided_sub_array[$i]; 
            }
        }                                               
    }    
}
print_r( $sum_divided_array );

If sum_divided_array is set, we are adding subarray value to it, if not, we are assigning current subarray to it.

Andrii Filenko
  • 954
  • 7
  • 17
  • My code works but it gives this "notice" with offset. Your code prints different result, I just want to sum the arrays according to those indexes. – Lucian Ardeleanu Feb 25 '19 at 14:38