Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined Index (Laravel)

I'm bashing my head against my desk trying to figure out why this PHP code is causing this error: Undefined index: arr. I'm using Laravel, and this code works like gold outside of it, but inside Laravel, it's returning the undefined index error.

Here's the code:

function set_pilots_array($line_array)
{
    $airports = $this->airports;
    $pilots = $this->pilots;
    foreach($airports as $airport)
    {
        if($airport == $line_array[11] || $airport == $line_array[13])
        {
            if($airport == $line_array[11])
            {
                $deparr = "dep";
            }
            if($airport == $line_array[13])
            {
                $deparr = "arr";
            }
            $this->pilots[$deparr][] = array($line_array[0], $line_array[11], $line_array[13], $line_array[7], $line_array[5], $line_array[6], $line_array[8]);
        }
    }
}

function get_pilots_count()
{
    $count = count($this->pilots['dep']) + count($this->pilots['arr']);
    return $count;
}

This sort of goes with my other question: Grab and Explode Data It's pulling the data from the data file using this code:

elseif($data_record[3] == "PILOT")
{
    $code_obj->set_pilots_array($data_record);
}

Which later does this:

$code_count = $code_obj->get_pilots_count();
like image 900
Dutchcoffee Avatar asked Aug 29 '12 15:08

Dutchcoffee


2 Answers

You do not have $this->pilots['arr'] set. In other words, if you look at the output of var_dump($this->pilots);, you shall see there is no arr key-value pair. I suggest you this fix:

$count = count((isset($this->pilots['dep']) ? $this->pilots['dep'] : array())) + count((isset($this->pilots['arr']) ? $this->pilots['arr'] : array()));

Actually, this is not a fix - this is more like a hack. To make your code correct i suggest you to set the default values for those $pilots['arr'] and $pilots['dep'] values:

function set_pilots_array($line_array)
{
    $airports = $this->airports;
    $pilots = $this->pilots;

    foreach (array('dep', 'arr') as $key) 
    {
        if (!is_array($pilots[$key]) || empty($pilots[$key])) 
        {
            $pilots[$key] = array();
        }
    }

    // ...
}
like image 135
shybovycha Avatar answered Sep 21 '22 01:09

shybovycha


Well there is too little code to really figure out what is going on, but based on what I see:

if($airport == $line_array[13])

this condition is never being met and so $deparr = "arr"; never happens and because of this

count($this->pilots['arr']);

is giving an undefined index error

You can easily suppress this by:

$count = count(@$this->pilots['dep']) + count(@$this->pilots['arr']);
like image 27
raidenace Avatar answered Sep 21 '22 01:09

raidenace