0

I am tring to create dinamically an associative array but I get undefined index. Cannot find the reason. I know the index doesn't exist, but I want to create it dinamically.

 foreach($lines as $line){
     $number = explode(",",$line)[1];//string
     $duration = explode(",",$line)[0];

     $seconds= getSeconds($duration);
     $phoneNumbersCalled[$number]+= $seconds;
     }
Stefano Maglione
  • 3,946
  • 11
  • 49
  • 96
  • 1) `$number = explode(",",$line)[1]; $duration = explode(",",$line)[0];` You can shorten this to: `list($duration, $number) = explode(",", $line);` (See [list()](http://php.net/manual/en/function.list.php)) 2) You probably get the error on this line: `$phoneNumbersCalled[$number]+= $seconds;`, because you try to add something to an undefined index. So check if that index already exists and if not set it to 0. – Rizier123 Jun 15 '16 at 20:25
  • I want to create this index dinamically, I am sure that doesn't exist – Stefano Maglione Jun 15 '16 at 20:26
  • Right now this line: `$phoneNumbersCalled[$number]+= $seconds;` is something like this: `undefined + number`. Now you can't add a number to undefined. So you first have to check if it exists and if not you have to initialize it with 0. So you then can add stuff to it with your code line. – Rizier123 Jun 15 '16 at 20:28

0 Answers0