映射在一个语句中初始化和递增

时间:2016-11-23 17:07:33

标签: php

如何在一行中增加地图条目,请参阅下面的注释。

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

1 个答案:

答案 0 :(得分:2)

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