TanGio
TanGio

Reputation: 766

Undefined offset for an array in php

I have the following code:

$count_table = array();
foreach ($events_tab as $event) {
    if(isset($event["nature"])){
        $count_table[$event["nature"]]++;
    }

}

The array events_tab is like this :

Array
(
     [0] => Array
       (
        [nature] => 300
        [id] => 100828698
    )

[1] => Array
    (
        [nature] => 3001
        [id] => 100828698
    )

)

I get the error : Undefined offset: 300 in this line : $count_table[$event["nature"]]++;. Please help me!! Thx in advance!!

Upvotes: 0

Views: 319

Answers (2)

Sougata Bose
Sougata Bose

Reputation: 31749

Check on $count_table if the key is set. It should be -

if(isset($count_table[$event["nature"]])){
    $count_table[$event["nature"]]++;
} else {
    $count_table[$event["nature"]] = 0;
}

Upvotes: 0

KTAnj
KTAnj

Reputation: 1356

$count_table = array();
foreach ($events_tab as $event) {

    if(isset($event["nature"])){
        if(!isset($count_table[$event["nature"]])){
            $count_table[$event["nature"]]=0;
        }
        $count_table[$event["nature"]]++;
    }
}

Upvotes: 2

Related Questions