Home > Blockchain >  Shorter way to add one to an array element OR set array element to 1?
Shorter way to add one to an array element OR set array element to 1?

Time:01-24

I often create scripts that generate reports that count a lot of different things while looping through mysql query results or lines of a file or something. In doing so, I usually have an array that keeps track of all the different "counts", like this:

$counts[$thingBeingCounted]  ;

So at the end I have an array with a bunch of counts that I can then report.

This works great, except PHP blows up on the first "count", since there is nothing to increment yet.

The obvious solution is to make sure it's set first:

if(!isset($counts[$thingBeingCounted])){
    $counts[$thingBeingCounted] = 0;
}
$counts[$thingBeingCounted]  ;

Or maybe

$counts[$thingBeingCounted] = isset($counts[$thingBeingCounted]) ? $counts[$thingBeingCounted]   1 : 1;

Either way, the "check if it's set first and then initialize it if needed" really takes away from the simpleness of just slapping on the end of the array element.

I can't just initialize the $counts array with all the potential things to be counted at the start either, as there can potentially be a lot of things it's counting.

Is there any more elegant solution?

CodePudding user response:

$counts["new_el"] = ($counts["new_el"] ?? 0)   1;

This is the shortest way to properly increment a variable without declaration.

If you really want to make the code more short, you can use error suppression (@$counts["element"] ) but it is not recommended or maybe one of forbidden thing that we should not do

For explanation,

$counts["new_el"] ?? 0

is the same as

isset($counts["new_el"]) ? $counts["new_el"] : 0

so my code above is equivalent to

$counts["new_el"] = (isset($counts["new_el"]) ? $counts["new_el"] : 0)   1

Sorry for bad English and bad format, i am new in this community and just trying to help another

  •  Tags:  
  • Related