← Back to all snippets
PHP

Verify if a Key Exists in a PHP Array

Efficiently check for the existence of a specific key within a PHP array using `array_key_exists()` to prevent errors and ensure data integrity in your applications.

<?php
$config = [
    'database' => 'mydb',
    'username' => 'root',
    'password' => 'secret'
];

// Check if 'database' key exists
if (array_key_exists('database', $config)) {
    echo "'database' key exists.
";
}

// Check if 'port' key exists
if (!array_key_exists('port', $config)) {
    echo "'port' key does not exist.
";
}

// Using isset() - Note the difference with null values
$dataWithNull = ['present_key' => 'value', 'null_key' => null];

if (array_key_exists('null_key', $dataWithNull)) {
    echo "array_key_exists finds 'null_key' even if value is null.
";
}

if (isset($dataWithNull['null_key'])) {
    echo "isset() finds 'null_key' (this won't print as value is null).
";
} else {
    echo "isset() does NOT find 'null_key' because its value is null.
";
}

// Check if 'non_existent_key' exists using isset()
if (!isset($dataWithNull['non_existent_key'])) {
    echo "isset() correctly identifies 'non_existent_key' as not set.
";
}
?>
How it works: The `array_key_exists()` function checks whether a specified key or index exists in an array. It returns `true` even if the key's value is `null`. In contrast, `isset()` checks if a variable is set and is not `null`. While `isset()` is often quicker for non-`null` checks, `array_key_exists()` is crucial when differentiating between a key not existing and a key existing with a `null` value.

Need help integrating this into your project?

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

Hire DigitalCodeLabs