On 26/01/2022 14:48, Christian Schneider wrote:
2) Hot take: I still consider the well-defined constructs like $count++ or 
$counts[$word]++ to be useful


I agree, particularly with regards array items rather than top-level variables. Last time this came up, I suggested that before promoting the error further, we find elegant solutions for the valid use cases.

For instance, the following code is safe, useful, and readable:

$countsByDayByCategory = [];
foreach ( $someData as $item ) {
    $countsByDayByCategory[ $item['day'] ][ $item['category'] ]++;
}

While there are definitely cases where spotting unset array keys would be useful, the current "fix" for this code leads to repetitive and hard to read code, which is probably *easier* to miss a mistake in:

$countsByDayByCategory = [];
foreach ( $someData as $item ) {
    $countsByDayByCategory[ $item['day'] ] ??= [];
    $countsByDayByCategory[ $item['day'] ][ $item['category'] ] ??= 0;
    $countsByDayByCategory[ $item['day'] ][ $item['category'] ]++;
}


Python has a "defaultdict" which lets you define the default for each dimension up front, rather than needing conditionals inside the loop, something like this:

$countsByDayByCategory = new DefaultDict(new DefaultDict(0));
foreach ( $someData as $item ) {
    $countsByDayByCategory[ $item['day'] ][ $item['category'] ]++;
}

I would be very interested in having something similar in PHP, and other suggestions to similar use cases, rather than just marching onwards with errors.


Regards,

--
Rowan Tommins
[IMSoP]

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to