Search with Precision using in_array() and array_search()

PHOTO EMBED

Thu Aug 14 2025 19:13:28 GMT+0000 (Coordinated Universal Time)

Saved by @agungnb #php

Checking if a value exists?
if (in_array('admin', $roles, true)) {
    // true === strict check, avoids weird type bugs
}

Need to find the key instead?
$key = array_search('editor', $roles, true);
// Returns: 'editor'

Always use the strict mode (true) – otherwise, PHP might return unexpected results due to loose comparisons (like “0" == false).

Pro tip: If you do lots of lookups, consider flipping the array so the value becomes the key – that’s way faster.
content_copyCOPY

array

https://medium.com/@catcatduatiga/php-arrays-like-a-pro-7-powerful-tricks-youll-wish-you-knew-sooner-92e33e836ed1