StevenOliver Posted November 13, 2018 Share Posted November 13, 2018 While looping through an array, using the Assingment Operator "+=" throws a "Notice: Undefined Index," but just using "=" will not throw a Notice. 1.) Why is that? 2.) Is there something more elegant than placing "if(!isset($animal['count'])) { $animal['count'] = ''; }" before the offending line of code? <?php error_reporting(E_ALL); ini_set('display_errors', 1); $_POST = array( 'horses' => '3', 'dogs' => '2' ); foreach($_POST as $var=>$value) { $animal['type'] = $var; $animal['count'] += $value; // Notice: Undefined index: count // but using $animal['count'] = $value; will not throw a Notice. } ?> Link to comment Share on other sites More sharing options...
kicken Posted November 13, 2018 Share Posted November 13, 2018 Because += involves reading the current value first, and you haven't yet defined any value for that index. $animal['count'] += $value is the same as $animal['count'] = $animal['count'] + $value If you know what keys you are using, then you can just initialize them to zero before your loop. $animal = ['count' => 0]; Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.