Suppose you need to create a ‘top’ of some sort and have code like this:
$matches=array();
foreach ($array as $v){
$matches[processing($v)]++;
}
This will output a Notice: Undefined index for the cases the index needs creating.
What would be the best way to tackle these cases since you KNOW you’ll have to create indexes?
I used these solutions depending on case:
- Suppressing the error
@$matches[$v]++;
Pro: VERY easy to type
Con: slow - Checking if it’s set
$matches[$v]=isset($matches[$v])?$matches[$v]++:1;
Pro: faster
Con: takes longer to write even in the shorthand form and need to use $matches[$v] 2 more times
Are there any other ways?
Looking for the fastest execution time as I’m using this function thousands of times or some lazier way to type that’s still faster than @
EDIT:
In a simple case where you have $matches[$v]++; you could also use array_count_values() (as Yoshi suggested)
After some reading, writing and testing I got something:
and thought I struck gold, but let’s see the tests first…
Test code:
Execution times: (for informative purposes only)
Conclusions:
@is of course the fastest to type and I don’t see any problem in using it in this case but feel free to check this question also: Suppress error with @ operator in PHPini_set()is worse than all on performanceinc()looks nice and clean, easy to type and does checking instead of suppressing, but calling it looks to be even slower than@isset()is slightly faster thanempty(), but both perform fairly the sameifstatements is slightly slower!array_fill()takes slightly longer thanfor?!?!RFC
I don’t consider this answer 100% complete, although, for now it looks like
isset()is the fastest and@the laziest.Any comments and ideas are appreciated!