php - Convert multiple if statements to a match() statement
Is it possible to replace all if
conditions with a match
construct?
If yes, how to do it?
$a = 1;
$b = 1.2;
$c = "xopa";
function filter($massive) {
foreach($massive as $items){
if(is_integer($items)){
echo "integer - {$items} <br>";
}
if(is_double($items)){
echo "floating point number - {$items} <br>";
}
if(is_string($items)){
echo "string - \"{$items}\" <br>";
}
}
}
filter([$a, $b, $c]);
Answer
Solution:
Yes, it is possible with match condition shortly like this:
<?php
$a = 1;
$b = 1.2;
$c = "xopa";
function filter($massive) {
foreach($massive as $item){
echo match(gettype($item)){
'integer' => "integer - $item",
'floot' => "float - $item",
'string' => "string - $item",
default => 'other type - '.$item
}.'<br>';
}
}
echo filter([$a,$b,$c]);
Source