Search code examples
arraysphp-8

Avoid Undefined Key Array warnings in PHP 8.x


I have some old (2004) PHP code that does things like:

$families[$new_row['family']]++;

Within a lot of other code in the while loop, this line's purpose is to count the number of unique families within a variable data set i.e. there may be one, or more likely several, families present in a few thousand rows from the database. It throws a warning ("Undefined Key Array") because the first time around $new_row['family'] is not previously set/initialised.

What is the best practice to achieve this kind of thing without a warning being thrown?

TIA,

Jools

PS I guess I am asking is there a simpler approach than:

if (isset($families[$new_row['family']]))
{
 $families[$new_row['family']]++;
}
else
{
 $families[$new_row['family']] = 1;
}

The above code would end up in a function, but even so, just want to check if there is another/better way.


Solution

  • You can do this in one line of code like:

    isset($families[$new_row['family']]) ? $families[$new_row['family']]++ : ($families[$new_row['family']] = 1)
    

    which clearly looks too complicated for the other people while debugging/reading the code, For me, the if-else is more readable.