CodexBloom - Programming Q&A Platform

advanced patterns with PHP 8.1's new `match` expression when used with arrays

๐Ÿ‘€ Views: 92 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-03
php php8 match-expression

I'm wondering if anyone has experience with I've searched everywhere and can't find a clear answer... Does anyone know how to This might be a silly question, but I'm working on a PHP 8.1 application where I need to use the new `match` expression to simplify my code for determining the status of a user based on their role. However, I'm working with unexpected behavior when using it with an array of roles. Hereโ€™s the code snippet that I've implemented: ```php $userRoles = ['admin', 'editor']; $status = match (true) { in_array('admin', $userRoles) => 'Admin User', in_array('editor', $userRoles) => 'Editor User', default => 'Guest User', }; echo $status; ``` The question arises when I run this code; I expect it to return `Admin User`, but it instead outputs `Guest User`. Iโ€™ve verified that the array contains the `admin` role, so Iโ€™m puzzled as to why `in_array` is not functioning as intended within the `match` statement. Iโ€™ve tried debugging by isolating the `in_array` calls outside of the `match` expression, and they return `true` as expected, so it seems to be an scenario with the scope or behavior of the `match` expression in this context. I also checked the PHP manual, but there is no mention of limitations when using expressions like `in_array` within `match`. Is this a known limitation, or am I missing something in my implementation? Any insights or workarounds would be greatly appreciated. My development environment is macOS. I'm coming from a different tech stack and learning Php. Any feedback is welcome! This issue appeared after updating to Php 3.10. I'm using Php latest in this project. Any suggestions would be helpful. Any ideas what could be causing this? Could someone point me to the right documentation?