Home > Mobile >  Is there a PHP equvalent to Python's Counter object?
Is there a PHP equvalent to Python's Counter object?

Time:10-08

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.

CodePudding user response:

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: 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;
}

CodePudding user response:

Try this :

Put '$' in front of 'i'. The code below must work

for ($i = 0; $i < numOfSomeResults; $i  ) {
    if (isset($otherResult[$i]) {
        echo $otherResult[$i];
    } else {
        echo 0;
    }
}
  • Related