PHP8 triggers a warning if an index in not set.
In PHP7 the following (very simplified) snippet used to be a 'dirty' but a very readable and working solution to count stuff according to their key on the fly (eg in re-indexing algorithms):
$keylist = array('keyA','keyB','keyA','keyA');
$idx_count = array();
foreach ($keylist as $thiskey){
$idx_count[$thiskey]++;
}
Solutions in PHP8 to require to check for existence of the index as in a check with isset():
$keylist = array('keyA','keyB','keyA','keyA');
$idx_count = array();
foreach ($keylist as $thiskey){
if (!isset($idx_count[$thiskey]){ $idx_count[$thiskey] = 0; }
$idx_count[$thiskey]++;
}
or a check with empty():
$keylist = array('keyA','keyB','keyA','keyA');
$idx_count = array();
foreach ($keylist as $thiskey){
if (empty($idx_count[$thiskey]){ $idx_count[$thiskey] = 0; }
$idx_count[$thiskey]++;
}
or with branching:
$keylist = array('keyA','keyB','keyA','keyA');
$idx_count = array();
foreach ($keylist as $thiskey){
if (!isset($idx_count[$thiskey]){
$idx_count[$thiskey] = 1;
}else{
$idx_count[$thiskey]++;
}
}
or using a null coalescing op:
$keylist = array('keyA','keyB','keyA','keyA');
$idx_count = array();
foreach ($keylist as $thiskey){
$idx_count[$thiskey] ??= 0;
$idx_count[$thiskey]++;
}
Questions:
1. Besides cluttering readability, how do these options impact the performance with very large $keylists?
In either case, it's an extra comparison on every loop, while the internal 'catch' in PHP7 (probably) only impacted the first iteration.
2. Is there an elegant way to make this readable and fast at the same time?
I know people hate the error-suppression operator, but you could use
Another option is to prefill the array with all the required keys before the loop.