PHP

Check If Array Contains Key-Value Pair

Verify the existence of a specific key and its corresponding value within an associative array in PHP, crucial for data integrity and conditional logic.

<?php

function arrayContainsKeyValuePair(array $array, string $key, $value): bool
{
    return isset($array[$key]) && $array[$key] === $value;
}

function arrayContainsNestedKeyValuePair(array $arrayOfArrays, string $key, $value): bool
{
    foreach ($arrayOfArrays as $subArray) {
        if (is_array($subArray) && isset($subArray[$key]) && $subArray[$key] === $value) {
            return true;
        }
    }
    return false;
}

$user = [
    'id' => 101,
    'name' => 'Jane Doe',
    'status' => 'active',
    'roles' => ['admin', 'editor']
];

$employees = [
    ['id' => 1, 'name' => 'John', 'department' => 'HR'],
    ['id' => 2, 'name' => 'Sara', 'department' => 'IT'],
    ['id' => 3, 'name' => 'Mike', 'department' => 'HR'],
];


// Example 1: Check a single associative array
$hasActiveStatus = arrayContainsKeyValuePair($user, 'status', 'active'); // true
$hasPendingStatus = arrayContainsKeyValuePair($user, 'status', 'pending'); // false
$hasNonExistentKey = arrayContainsKeyValuePair($user, 'address', '123 Main St'); // false

// Example 2: Check an array of associative arrays
$itEmployeeExists = arrayContainsNestedKeyValuePair($employees, 'department', 'IT'); // true
$marketingEmployeeExists = arrayContainsNestedKeyValuePair($employees, 'department', 'Marketing'); // false

// var_dump($hasActiveStatus, $hasPendingStatus, $hasNonExistentKey);
// var_dump($itEmployeeExists, $marketingEmployeeExists);
How it works: This snippet provides two utility functions. `arrayContainsKeyValuePair` checks if a single associative array has a specific key and if its value exactly matches a given value. `arrayContainsNestedKeyValuePair` extends this to an array of associative arrays, iterating through each sub-array to find if any of them contain the specified key-value pair. Both functions return a boolean, making them useful for validation or conditional logic.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs