Jump to content

UNDEFINED INDEX with += Assignment Operator


StevenOliver

Recommended Posts

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.