I found another way to increment undefined array items. It looks like a kind of a hack, but it's obvious and still short.
Suppose you need to increment a leaf value of the few nested arrays. Using isset()
it may be too annoying:
<?php
error_reporting(E_ALL);
$array['root']['node'][10]['node'][20]['leaf'][30]['totalCount'] =
isset($array['root']['node'][10]['node'][20]['leaf'][30]['totalCount'])
? ($array['root']['node'][10]['node'][20]['leaf'][30]['totalCount'] + 1)
: 1;
Name of an array item repeated there three times, rippling in your eyes.
Try to use &
operator to get an array item reference. Acting with a reference not causing any notices or errors:
<?php
error_reporting(E_ALL);
$item = &$array['root']['node'][10]['node'][20]['leaf'][30]['totalCount'];
// $item is null here
$item++;
unset($item);
echo $array['root']['node'][10]['node'][20]['leaf'][30]['totalCount']; // 1
It works just fine, but you can also avoid null
to 0
casting:
<?php
error_reporting(E_ALL);
$item = &$array['root']['node'][10]['node'][20]['leaf'][30]['totalCount'];
// $item is null here
$item = isset($item) ? ($item + 1) : 1;
unset($item);
echo $array['root']['node'][10]['node'][20]['leaf'][30]['totalCount']; // 1
If you're already on PHP7, use coalesce operator instead of isset()
:
$item = ($item ?? 0) + 1;