PASSWORD RESET

Your destination for complete Tech news

How to check if a key exist in Laravel collection?

1.38K 0
< 1 min read

To check if a key exists in a Laravel collection, you can use the has method. This method will return true if the key exists in the collection, and false if it doesn’t.

Here’s an example:

$collection = collect(['a' => 1, 'b' => 2, 'c' => 3]);
$exists = $collection->has('a');

// $exists is now true

You can also use the offsetExists method, which is an alias of the has method:

$collection = collect(['a' => 1, 'b' => 2, 'c' => 3]);
$exists = isset($collection['a']);

// $exists is now true

Note that the has and offsetExists methods will only check for the existence of the key in the top-level of the collection. If you want to check for the existence of a key in a deeply nested collection, you can use a recursive function to do so:

function recursiveHas($collection, $key)
{
    if ($collection->has($key)) {
        return true;
    }

    foreach ($collection as $item) {
        if (is_array($item) || $item instanceof Collection) {
            if (recursiveHas($item, $key)) {
                return true;
            }
        }
    }

    return false;
}

$collection = collect([
    'a' => [
        'b' => [
            'c' => 1,
            'd' => 2,
        ],
        'e' => 3,
    ],
    'f' => 4,
]);

$exists = recursiveHas($collection, 'c');

// $exists is now true

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.