0

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!!

6
  • 3
    $count_table[300] isn't set, but you're trying to increment the value that it holds..... how can you increment a value that doesn't exist? Commented May 22, 2015 at 9:18
  • What do you want exactly? Commented May 22, 2015 at 9:19
  • 3
    Replace $count_table[$event["nature"]]++; with isset($count_table[$event["nature"]]) ? $count_table[$event["nature"]]++ : $count_table[$event["nature"]] = 1; Commented May 22, 2015 at 9:19
  • Increment the array : $count_table Commented May 22, 2015 at 9:19
  • Or even replace the whole thing with a simple: $count_table = array_count_values(array_column($events_tab, 'nature', 'nature')); should work with recent versions of PHP Commented May 22, 2015 at 9:22

2 Answers 2

2
$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"]]++;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.