tdc
tdc

Reputation: 5464

Undefined Offset: 1 while iterating through an array

This is a relatively simple problem, but I would appreciate some insight into what is going on to give me this error. Bellow is the code that is throwing the error:

    foreach($courseArray[0] as $value)
    {
        list( $courseQuarter,$coursePrefix ) = explode( "-", $value );
        if( $courseQuarter == get_current_yearquarter()) 
        {
                array_push( $return, $value );
        }
    }

The error specifically is from the list() line.

Here is a var_export() of $courseArray:

array ( 0 => array( 
          'count' => 15, 
          0 => '20103-0610-442-01', 
          1 => '20103-0508-446-01', 
          2 => '20103-0501-406-01', 
          3 => '20104-0660-499-01', 
          4 => '20111-0307-782-70', 
          5 => '20111-0610-870-01', 
          6 => '20111-0621-504-01', 
          7 => '20112-0621-513-01', 
          8 => '20112-0303-762-90', 
          9 => '20112-0101-794-71', 
          10 => '20112-0610-710-90', 
          11 => '20113-0307-770-70', 
          12 => '20113-0610-820-01', 
          13 => '20113-0617-631-01', 
          14 => '2121-0106-744-01', 
      ), 
);

Thank you for any help in fixing my code :) I think I could use an explanation of offsets and how they relate to arrays.

Upvotes: 1

Views: 390

Answers (1)

msEmmaMays
msEmmaMays

Reputation: 1063

it will foreach over the 'count' element, which doesn't have a '-' in it.

foreach($courseArray[0] as $key => $value)
{
    if ($key == 'count') {continue;} // <- skip the 'count' key
    list( $courseQuarter,$coursePrefix ) = explode( "-", $value );
    if( $courseQuarter == get_current_yearquarter()) 
    {
            array_push( $return, $value );
    }
}

Upvotes: 3

Related Questions