0

There are 4 variables, they all store numbers (numbers in the form of different representations) All of these variables were placed in an unnamed array to test the type of the variables. Inside the loop, there are 2 conditions that only work on certain variables ($a and $b).

The question is how to do the same in a match? Namely, I'm interested in the implementation of several conditions (with the && operator) in match.

How to do it in a match:

if(is_integer($items) && $items == 1){}
elseif(is_numeric($items) && $items == 1.2){}

code with if:

$a = 1;
$b = 1.2;
$c = "1.5";
$d = 25;
 
function filter($massive) {
 
foreach($massive as $items){     
            
if(is_integer($items) && $items == 1){          // works only with $a variable
echo "integer - {$items}";
}
 
elseif(is_numeric($items) && $items == 1.2){    // only $b
echo "numeric  -{$items}";
}
 
else{
echo "other types - $items" ;
}echo"<br>";
}}
 
filter([$a, $b, $c, $d]);

My attempt with match:

$a = 1;
$b = 1.2;
$c = "1.5";
$d = 25;
 
function filter($massive) {

foreach($massive as $items){                                                 
            
echo match(true){  

is_integer($items) => "integer -{$items}",  
is_numeric($items) => "numeric - {$items}", 
default =>  "other types - {$items}",                                                  
 
}."<br>";
 
}}
 
filter([$a, $b, $c, $d]);
deceze
  • 510,633
  • 85
  • 743
  • 889
Ice time
  • 3
  • 3

1 Answers1

0

Yes, you can use the logical AND (&&) operator in PHP match. If you get a syntax error about T_DOUBLE_ARROW, and you are sure you don't have a missing or extra opening or closing bracket or parenthesis, then it is possible that your PHP version is too old and you should either upgrade PHP to at least version 8 or use switch instead. match is a php8 feature.

<?php
$a = 1;
$b = 1.2;
$c = "1.5";
$d = 25;

function filter($massive) {
    foreach($massive as $items){
        echo match($items){  
            is_integer($items) && $items == 1 => "integer -{$items}",  
            is_numeric($items) && $items == 1.2 => "numeric - {$items}", 
            default =>  "other types - {$items}",
        }."<br>";
    }
}

filter([$a, $b, $c, $d]);
?>
Nathan Mills
  • 2,243
  • 2
  • 9
  • 15