0

In my code (with php notice errorhandling) I have lots of these blocks inside loops:

$someVar=array();
...
foreach (...){
  if(!isset($someVar["something"])){
    $someVar["something"]=0;
  }
  $someVar["something"]++;
}

another solution would be to ignore the notice with @

@$someVar["something"]++

which is not very clean.

is there a cleaner way to initialize a variable with 0 only if not set?

rubo77
  • 19,527
  • 31
  • 134
  • 226
  • Try a ternary? `$someVar = isset($someVar) ? ++$someVar : 0` – aynber Jun 23 '17 at 15:00
  • 2
    The solution is to *initialise the variable*, then this problem solves itself. – deceze Jun 23 '17 at 15:00
  • 1
    What if `foreach` runs over an empty array and the variable is not set? The code after `foreach` has the same problem. The correct solution is to initialize all the variables before using them. Initialize `$someVar = 0` before the `foreach` and that's all. Cleaner code. – axiac Jun 23 '17 at 15:02
  • Short hand like `$someVar = $someVar++ ?: 0;` - Or initialise the variable explicit like `$someVar = 0; foreach $someVar++; endforeach;` – daan.desmedt Jun 23 '17 at 15:02
  • 1
    Woo code golf! `$x=($x??0)+1;` :) – Alex Howansky Jun 23 '17 at 15:05

0 Answers0