0

How can I increment a map entry in one line, see comment below.:

$results = array();

# ...  compute $results

# I would like to replace below with one statement, is it possible?
if (!array_key_exists("cnt", $results)) {
   $results["cnt"] = 1; # first time
} else {
   $results["cnt"] += 1;
}
2
  • 1
    Assign it to 1 when you initialize it?
    – chris85
    Nov 23, 2016 at 17:12
  • Reducing the amount of code for no good reason is usually a bad idea
    – user557846
    Nov 23, 2016 at 17:13

1 Answer 1

2
<?php
    $results["cnt"] = !array_key_exists("cnt", $results) ? 1 :  $results["cnt"] + 1;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.