Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Conditional selection (?:)

Choose one of two expressions according to the boolean value of the condition.

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

Syntax

$test ? $whenTrue : $whenFalse

Choose one of two expressions according to the boolean value of the condition. Only the selected expression is evaluated. The short form returns the first value itself when it is truthy and otherwise evaluates the fallback. Consequently a string consisting of one zero selects the fallback even though it is present. Since PHP 8, chaining full ternaries as a ? b : c ? d : e without grouping parentheses is rejected. Short chains such as a ?: b ?: c remain valid.

$test ? $whenTrue : $whenFalse
["empty","default","0"]

Examples

<?php
$quota = '0';
$label = $quota === '0' ? 'empty' : 'available';
echo json_encode([$label, $quota ?: 'default', $quota ?? 'default']);

Result

["empty","default","0"]

Sources