I have some old (2004) PHP code that does things like:
我有一些旧的(2004)PHP代码,其功能如下:
$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.
在While循环中的许多其他代码中,此行的目的是计算变量数据集中的唯一家族的数量,即数据库中的几千行中可能存在一个或几个家族。它抛出一个警告(“UNDEFINED KEY数组”),因为第一次在$NEW_ROW[‘FAMILY’]附近没有预先设置/初始化。
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.
上面的代码将在一个函数中结束,但即便如此,也只是想检查是否有其他/更好的方法。
更多回答
优秀答案推荐
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.
在调试/读取代码时,这显然对其他人来说太复杂了,但对我来说,if-Else更具可读性。
更多回答
我是一名优秀的程序员,十分优秀!