Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Conditional default assignment (??=)

Initialize a writable target only when it is missing or currently null.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

$settings['key'] ??= $fallback

Initialize a writable target only when it is missing or currently null. The fallback expression runs only when the assignment is required. A stored false value, zero or empty string is retained. This is useful for initializing an optional cache slot without overwriting a previously calculated zero.

$settings['key'] ??= $fallback
[{"score":0,"page":1},1]

Examples

<?php
$cache = ['score'=>0, 'page'=>null];
$calls = 0;
$cache['score'] ??= ++$calls;
$cache['page'] ??= ++$calls;
echo json_encode([$cache,$calls]);

Result

[{"score":0,"page":1},1]

Sources