-1

I'm trying to count the occurence of a string in multidimentional array and get it.

So I found this : http://php.net/manual/fr/function.array-count-values.php and an exemple in the "User Contributed Notes".

Here my code :

$count_values = array();
foreach ($Bigtable as $a)
{
    foreach ($a as $table)
    {
        $count_values[$table]++;             // line 32
    }
}
asort($count_values,SORT_NUMERIC );
$onet_code=end ($count_values);

Here my error: Notice: Undefined index: 11-1011.00 in /home/goldiman1/www/postQuestion.php on line 32

I think that the error is in the last line when I try to get the string.

What do you guys think about it?

Thank you

Goldiman

Edit: Thank you everybody for your help ! All solutions work like a charm and I understood what was the issue, it was easier to understand Kasia answer because i'm more familiar with isset()

goldiman
  • 189
  • 2
  • 13

3 Answers3

4
$count_values[$table]++;

This line is trying to increment the value in $count_values[$table] - but you never initialize that value in the first place!

You need to change this code to create the value at 1 if it doesn't already exist, and only increment it if it does exist.

Tim B
  • 40,716
  • 16
  • 83
  • 128
2

If $table exists on the array(key) then increment the value else create new one. Try this -

foreach ($Bigtable as $a)
{
    foreach ($a as $table)
    {
        if (array_key_exists($table, $count_values)) {
            $count_values[$table]++;
        } else {
            $count_values[$table] = 1;
        }
    }
}
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
  • 1
    I was trying to point him in the right direction without giving him the full solution. Still, this answer is more complete than mine so +1 :) – Tim B Apr 22 '15 at 12:43
1

by default $count_values[$table] won't be set

foreach ($a as $table)
{
    if(isset($count_values[$table])){
        $count_values[$table]++;
    } else {
        $count_values[$table] =1
    }
}
Kasia Gogolek
  • 3,374
  • 4
  • 33
  • 50