Search code examples
php-8

How in php8 make match with more complicated conditions?


As php8 allows match like :

echo match ($v) {
    0 => 'Foo',
    1 => 'Bar',
    2 => 'Baz',
};  // Bar

I wonder if there is a way to use in match more complicated conditions, like :

  if ($checkValueType == EnumType::Integer and ! isValidInteger($value) and ! empty
        ($default_value)) {
        return $default_value;
    }
    if ($checkValueType == EnumType::Float and ! isValidFloat($value) and ! empty($default_value)) {
        return $default_value;
    }
    if ($checkValueType == EnumType::Bool and ! isValidBool($value) and ! empty($default_value)) {
        return $default_value;
    }

    return $value;

Thanks in advance!


Solution

  • No, you can't do that, because match is an expression, and cannot contain statements.

    Structure of a match expression

    $return_value = match (subject_expression) {
        single_conditional_expression => return_expression,
        conditional_expression1, conditional_expression2 => return_expression,
    };