Base de connaissancesCentre d’examen
FRFrançais
Choisir la langue13

CKTIS / PHP

Conditions et branchements

if convertit sa condition en bool, donc 0 et «0» sautent la branche vraie. match compare strictement valeur et type et évalue uniquement le bras choisi.

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

Syntaxe

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

if convertit sa condition en bool, donc 0 et «0» sautent la branche vraie. match compare strictement valeur et type et évalue uniquement le bras choisi. Sans correspondance ni default il lève UnhandledMatchError. Les conditions des bras sont évaluées dans l’ordre jusqu’au premier succès. Seule l’expression de résultat à droite du bras choisi est exécutée.

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"]]

Exemples

<?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]);

Résultat

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

Sources