Jump to content

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.
}

?>

 

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 by kicken
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.