In Python, there exists a Counter
class that allows me to do this:
counter = Counter()
counter[2] = 5
counter[3] = 2
for i in range(5):
print(f'counter[{i}]={counter[i]}')
Which will give me the following output:
counter[0]=0
counter[1]=0
counter[2]=5
counter[3]=2
counter[4]=0
Basically it acts as if any element in the dictionary that has not been explicitly initialized has the value of zero, and will never throw an exception when accessing non-existing element.
Is there a similar entity in PHP, or is the only way to check each index when accessing in a loop?
I am looking for a way to avoid doing this:
for ($i = 0; $i < numOfSomeResults; $i++) {
if (isset($otherResult[$i]) {
echo $otherResult[$i];
} else {
echo "0";
}
}
And do something like:
for ($i = 0; $i < $numOfSomeResults; $i++) {
echo $counter[i];
}
Both the indexes and values I need to work with are integers if that helps.
Without reinventing the wheel and following on from Alex's comment, you can use the null coalescing operator (PHP 7+)
for ($i = 0; $i < $numOfSomeResults; $i++) {
echo $counter[$i] ?? 0;
}
Some background information about what it does: The null Coalescing operator is mainly used to avoid the object function to return a NULL value rather returning a default optimized value. It is used to avoid exception and compiler error as it does not produce E-Notice at the time of execution.
(Condition) ? (Statement1) ? (Statement2);
This same statement can be written as:
if ( isset(Condition) ) {
return Statement1;
} else {
return Statement2;
}