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. } ?> Quote Link to comment https://forums.phpfreaks.com/topic/307891-undefined-index-with-assignment-operator/ Share on other sites More sharing options...
kicken Posted November 13, 2018 Share Posted November 13, 2018 (edited) 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]; Edited November 13, 2018 by kicken Quote Link to comment https://forums.phpfreaks.com/topic/307891-undefined-index-with-assignment-operator/#findComment-1562114 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.