Get Intersection of Two Arrays
Returns scalar values that exist in both arrays using strict comparison.
Purpose
Returns scalar values that exist in both arrays using strict 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.
*/
/**
* Get Intersection of Two Arrays.
*
* Purpose:
* Finds scalar values shared by two arrays.
*
* @param array $first First value list.
* @param array $second Second value list.
* @return array Shared values.
*/
function ogSnippetGetArrayIntersection(array $first, array $second): array {
$intersection = array();
foreach ($first as $value) {
if (is_scalar($value) === false) {
continue;
}
if (in_array($value, $second, true) === true && in_array($value, $intersection, true) === false) {
$intersection[] = $value;
}
}
return $intersection;
}
$shared_routes = ogSnippetGetArrayIntersection(array('Mars', 'Ceres', 'Tycho'), array('Earth', 'Ceres', 'Luna'));
echo 'Shared Expanse route count: '.count($shared_routes);