Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Conditional control flow

An if test converts its condition to bool.

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

Syntax

if ($value) { /* branch */ }
match ($value) { 0 => "zero", default => "other" };

An if test converts its condition to bool. The integer 0 and string "0" both skip the true branch. A match expression instead compares its subject with each arm using strict identity and evaluates only the selected result. Without a matching arm or default it throws UnhandledMatchError. Arm conditions are evaluated in order up to the first match. Only the selected right-hand result expression runs.

function classify($v){$branch="no"; if($v){$branch="yes";} return [$branch,match($v){0=>"int","0"=>"text",default=>"other"}];}
echo json_encode([classify(0),classify("0"),classify("00")]);
$trace=[]; $mark=function($tag,$v)use(&$trace){$trace[]=$tag;return $v;}; $r=match(2){$mark("c1",1)=>$mark("r1","A"),$mark("c2",2)=>$mark("r2","B"),$mark("c3",3)=>"C"};echo "\n",json_encode([$r,$trace]);
[["no","int"],["no","text"],["yes","other"]]
["B",["c1","c2","r2"]]

Examples

<?php
function classify($v){$branch="no"; if($v){$branch="yes";} return [$branch,match($v){0=>"int","0"=>"text",default=>"other"}];}
echo json_encode([classify(0),classify("0"),classify("00")]);
$trace=[]; $mark=function($tag,$v)use(&$trace){$trace[]=$tag;return $v;}; $r=match(2){$mark("c1",1)=>$mark("r1","A"),$mark("c2",2)=>$mark("r2","B"),$mark("c3",3)=>"C"};echo "\n",json_encode([$r,$trace]);

Result

[["no","int"],["no","text"],["yes","other"]]
["B",["c1","c2","r2"]]

Sources