Skip to content
← Back to Snippets
Code

Check if Key Exists in an Array

Checks an associative array for a key with array_key_exists() and returns the value only when present.

Purpose

Checks an associative array for a key with array_key_exists() and returns the value only when present.

Snippet details

ContextArrayLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Forms and Validation

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Check if Key Exists in an Array.
 *
 * Purpose:
 * Checks whether a specific key exists, even when the value is null.
 *
 * @param array $values Associative array.
 * @param string $key Key to find.
 * @return array Key lookup result.
 */
function ogSnippetCheckIfKeyExistsInArray(array $values, string $key): array {
	$exists = array_key_exists($key, $values);
	$value = null;

	if ($exists === true) {
		$value = $values[$key];
	}

	return array(
		'key' => $key,
		'exists' => $exists,
		'value' => $value
	);
}

$ship = array('name' => 'Rocinante', 'drive' => 'Epstein');
$key_report = ogSnippetCheckIfKeyExistsInArray($ship, 'drive');

$key_exists_text = 'no';

if ($key_report['exists'] === true) {
	$key_exists_text = 'yes';
}

echo 'Drive key exists: '.$key_exists_text;