Search code examples
phpundefined-index

Undefined Index of array


I'm trying to figure out why I'm getting an undefined index in the view for this line:

<?php if ($allies[''] == 'No Wrestlers In Database') {

Controller:

if (empty($rosterList)) {
        $allies[] = 'No Wrestlers In Database';
}
else
{
        $allies[] = 'Please Select An Option';
        foreach ($rosterList AS $ally)
        {
            $allies[$ally->id] = $ally->rosterName;
        }
}

View:

<?php if ($allies[''] == 'No Wrestlers In Database') {
    echo $allies[''];
}
else {
    echo form_dropdown( 'ally1', $allies, $alliesList->ally1ID);
} ?>

EDIT :

I'm trying to figure out why my first dropdown isn't showing the correct value. alliesList print_r

Array
(
[0] => stdClass Object
    (
        [id] => 1
        [rosterListID] => 1
        [ally1ID] => 2
        [ally2ID] => 3
        [ally3ID] => 2
        [ally4ID] => 3
        [ally5ID] => 2
    )

)

allies print_r

Array
(
[0] => Please Select An Option
[1] => Kid Wonder
[3] => Oriel
[2] => Test Character
 )

EDIT 2:

Here's what I made it but getting an error in my view file that says trying to get property of non object.

//Get member's allies
    $alliesList = $this->bios->getRosterAlliesByRosterID($this->session->userdata('defaultRosterListID'));
    echo "<pre>";
    print_r($alliesList);
    echo "</pre>";
    // Get list of members
    $rosterList = $this->bios->getAllRoster();
    $allies = array();
    if (empty($rosterList)) {
        $allies[''] = 'No Wrestlers In Database';
    }
    else
    {
        $allies[''] = 'Please Select An Option';
        foreach ($rosterList AS $ally)
        {
            $allies[$ally->id] = $ally->rosterName;
        }
    }
    echo "<pre>";
    print_r($alliesList);
    echo "</pre>";  

<?php echo form_label( 'Ally 1', 'ally1'); ?>
<div>
    <?php if (in_array('No Wrestlers In Database', $allies)) {
         echo 'No Wrestlers In Database';
    }
    else {
         echo form_dropdown( 'ally1', $allies, $alliesList->ally1ID);
    } ?>
</div>

Solution

  • Because when assigning, the assignment index is incremented from 0 to n in arrays. So, you'll need this:

     if ($allies[0] == 'No Wrestlers In Database')