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!!
asked May 22, 2015 at 9:17
TanGio
7662 gold badges12 silver badges34 bronze badges
2 Answers 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"]]++;
}
}
answered May 22, 2015 at 9:28
KTAnj
1,3561 gold badge15 silver badges36 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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;
}
answered May 22, 2015 at 9:25
Sougata Bose
31.8k8 gold badges52 silver badges89 bronze badges
Comments
lang-php
$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?$count_table[$event["nature"]]++;withisset($count_table[$event["nature"]]) ? $count_table[$event["nature"]]++ : $count_table[$event["nature"]] = 1;$count_table$count_table = array_count_values(array_column($events_tab, 'nature', 'nature'));should work with recent versions of PHP