Check if Value Exists in an Array
Checks whether a value exists in an array using strict in_array() comparison.
Purpose
Checks whether a value exists in an array using strict in_array() comparison.
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 Value Exists in an Array.
*
* Purpose:
* Checks for a value with strict comparison.
*
* @param array $values Source values.
* @param string $needle Value to find.
* @return array Value lookup result.
*/
function ogSnippetCheckIfValueExistsInArray(array $values, string $needle): array {
$exists = in_array($needle, $values, true);
return array(
'needle' => $needle,
'exists' => $exists
);
}
$crew = array('Kirk', 'Spock', 'Uhura');
$value_report = ogSnippetCheckIfValueExistsInArray($crew, 'Spock');
if ($value_report['exists'] === true) {
echo 'Crew member found.';
} else {
echo 'Crew member missing.';
}