Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Keyword switch

Evaluate the subject once and search case labels using loose equality.

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

Syntax

switch ($subject) { case $value: /* statements */ break; }

Evaluate the subject once and search case labels using loose equality. Execution continues from the first match until break or the end, even across other labels. A default handles otherwise unmatched input. Check types first when "1" and 1 have different meanings.

function route($v){$out=""; switch($v){case 1:$out.="A"; case 2:$out.="B"; break; default:$out.="D";}return $out;}
echo json_encode([route("1"),route(2),route(9)]);
["AB","B","D"]

Examples

<?php
function route($v){$out=""; switch($v){case 1:$out.="A"; case 2:$out.="B"; break; default:$out.="D";}return $out;}
echo json_encode([route("1"),route(2),route(9)]);

Result

["AB","B","D"]

Sources