bobcat
bobcat

Reputation: 165

Undefined index errors when using plus equal operator

I'm working on another developers old code and there are tons of Notice: Undefined index errors when data is being set using the += operator. Essentially the index is not set yet in the array so the error is generated.

Example:

$myArray = array();
$myValue = 1;
for ($i = 1; $i <= 10; $i++) 
{
    $myArray['test'] += 1;
}

Will generate an error on the first run since the test index is not set yet.

I know I can remove this error with the following code:

$myArray = array();
$myValue = 1;
for ($i = 1; $i <= 10; $i++) 
{
    if ( ! isset($myArray['test']) )
    {
        $myArray['test'] = $myValue;
    } 
    else 
    {
        $myArray['test'] += $myValue;
    }
}

However, there are around 50 of things like this to change. Is it worth writing all these isset statements or is there a better way I am not aware of?

EDIT: I should note that the array indexes aren't always the same and sometimes aren't set so I can't preset the index in this circumstance to avoid the error.

Upvotes: 3

Views: 2666

Answers (3)

Tyler V.
Tyler V.

Reputation: 2561

If you are using PHP 7 and above, you can use the Null Coalescing Operator to make this code cleaner.

$myArray = [];
$myValue = 1;
for ($i = 1; $i <= 10; $i++) 
{
    $myArray['test'] = $myValue + ($myArray['test'] ?? 0);
}

The benefit here is not only that the code is cleaner, but you're also being more explicit about the default value (0)

Upvotes: 4

WOLFF
WOLFF

Reputation: 586

Old/Deprecaded/Unrecommended but the shortest solution is

@$myArray['test'] += $myValue;

Upvotes: 0

luttkens
luttkens

Reputation: 1264

This is a bit shorter, but perhaps still a bit complicated if you have many edits.

$myArray = array();
$myValue = 1;
for ($i = 1; $i <= 10; $i++) 
{
    isset($myArray['test']) ? $myArray['test'] += $myValue : $myArray['test'] = $myValue;

}

You could also write a global function (not tested)..

$myArray = array();   
$myValue = 1;
for ($i = 1; $i <= 10; $i++) 
{
    increment($myArray['test'], $myValue);
}

function increment(&$var, $inc){
    $var = isset($var) ? $var += $inc : $var = $inc
}

Upvotes: 5

Related Questions