Joe Shanahan
Joe Shanahan

Reputation: 816

Strange behavior: Undefined index whilst index IS correct

I'm trying to access a value from an array that is 3 levels deep yet PHP is reporting that the index is undefined whilst it certainly is. Unset using the same index works fine!

Code:

function CleanUpCharacters($c) //Remove unneeded information
{   
    for ($i = 0; $i < count($c); ++$i)
    {
        $c[$i]['character']['rank'] = $c[$i]['rank']; // Move rank in to char
        $c[$i] = $c[$i]['character']; // Move subarray char's keys/values to parent array

        unset($c[$i]['battlegroup']);
        unset($c[$i]['level']);
        unset($c[$i]['achievementPoints']);
        unset($c[$i]['thumbnail']);

        $c[$i]['specName'] = $c[$i]['spec']; // <--- Undefined index notice
        unset($c[$i]['spec']); // <--- Works fine, no errors

        unset($c[$i]['guild']);
        unset($c[$i]['guildRealm']);
    }

    return $c;
}

The line causes the error is actually $c[$i]['specName'] = $c[$i]['spec']['name']; I removed ['name'] to see if that fixed the issue but it did not.

Here's a screenshot of the unfiltered array, $c:

enter image description here

Upvotes: 0

Views: 130

Answers (2)

Jens A. Koch
Jens A. Koch

Reputation: 41756

unset() always works. It has no return value and it won't raise an error or notice.

Unset example with undefined var: http://ideone.com/4OcSkQ

<?php 
unset($a);

In your code, you need a key existance check, before you can do the assignment.

    $c[$i]['specName'] = $c[$i]['spec']; // <--- Undefined index notice

becomes

    if(array_key_exists('spec', $c[$i]) === true) { // test, if spec key exists
       $c[$i]['specName'] = $c[$i]['spec'];         // assign from spec to specName
    }

If you need to log or process the opposite case (when spec is missing), you might add an else:

    else {
        echo 'Key "spec" was not found. Working on: ' . $i['name'] . '<br>';
    }

Also you can delete more then one variable with unset(), like so:

    unset(
       $c[$i]['battlegroup'], 
       $c[$i]['level'], 
       $c[$i]['achievementPoints'], 
       $c[$i]['thumbnail']
    );

Upvotes: 1

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

I don't see any error here. It seems that for some records spec may be not set. You can check it changing:

for ($i = 0; $i < count($c); ++$i) {

into

for ($i = 0; $i < count($c); ++$i) {
   if (!isset($c[$i]['character']['spec']) {
       echo "no spec in array! for ".$i."<br />";
   }

Upvotes: 1

Related Questions