Skip to Content
Course content

93: in_array and array_search

Click on the "Edit" button in the top corner of the screen to edit your slide content.

How do I just check if a specific value exists in my array?

If all you care about is a "yes" or "no" answer, in_array() is your best friend. It returns a boolean—true if the value is there, false if it isn't. I use this constantly for simple permission checks or validating that a user's input matches a list of allowed options.

$allowed_roles = ['admin', 'editor', 'moderator'];
$user_role = 'editor';

if (in_array($user_role, $allowed_roles)) {
    echo "Access granted!";
} else {
    echo "You don't have permission to be here.";
}

If I find a value, how do I know exactly where it is?

Sometimes knowing that a value exists isn't enough; you need to know where it is so you can manipulate it or reference its key. That's where array_search() comes in. Instead of a boolean, it returns the key of the first matching element it finds.

Imagine you're managing a shopping cart where the keys are product IDs and the values are the product names. If you have the name but need the ID to update the database, array_search() is the tool for the job.

$cart = [
    101 => 'Mechanical Keyboard',
    105 => 'Gaming Mouse',
    210 => 'UltraWide Monitor'
];

$search_term = 'Gaming Mouse';
$product_id = array_search($search_term, $cart);

if ($product_id !== false) {
    echo "Found it! The product ID is: " . $product_id; 
    // Output: Found it! The product ID is: 105
}

Why is my search returning true when the types don't even match?

This is a classic PHP "gotcha." By default, both in_array() and array_search() are "loose." This means they use standard equality (==), so the string "1" is considered equal to the integer 1. In a large project, this can lead to some really frustrating bugs.

To fix this, both functions take an optional third parameter: strict. Set this to true, and PHP will use identity comparison (===), checking both the value and the type.

$ids = [10, 20, 30];
$input = "10";

// Loose check (default) - returns true
var_dump(in_array($input, $ids)); 

// Strict check - returns false because "10" (string) is not 10 (int)
var_dump(in_array($input, $ids, true)); 

Wait, why is array_search returning false when the item is at the start of the array?

I've seen a lot of developers trip over this. Since array_search() returns the key, and the first index of an array is often 0, a simple if (!array_search(...)) check will fail. In PHP, 0 is "falsy," so the code thinks the item wasn't found when it actually was—it was just at the very beginning.

You must use the strict inequality operator (!==) when checking the result of array_search() to distinguish between the integer 0 and the boolean false.

$colors = ['red', 'blue', 'green'];
$index = array_search('red', $colors);

// WRONG: This will treat index 0 as false
if (!$index) {
    echo "Not found!"; 
}

// RIGHT: This specifically checks if the result is the boolean value false
if ($index !== false) {
    echo "Found at index: " . $index;
}



📋 Practical Task

Exercise: Building a Restricted Page Access Guard

You are building a simple access control system for a blog. You have an array of $authorized_users (their usernames) and a $priority_list where the index represents their level of authority (0 being the highest).

Your Task:

  • Create an array called $authorized_users containing at least 4 usernames.
  • Create a separate array called $priority_list where the values match those usernames in order of priority.
  • Create a variable $current_user and assign it a username.
  • Use in_array() to check if the $current_user is authorized.
  • If they are authorized, use array_search() to find their priority level from the $priority_list and print: "Access granted. Your priority level is: [index]."
  • If they are not authorized, print: "Access denied."
  • Bonus: Test your code with a user who is at index 0 of the priority list to ensure your array_search() logic doesn't accidentally trigger an "Access denied" message.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.