Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
function haystackContainsNeedle($haystack, $needle) {
$intersection = array_intersect_assoc($haystack, $needle);
return $intersection == $needle ? 'true' : 'false';
}
$haystack = [
"firstName" => "Adam",
"lastName" => "Cameron",
"role" => "dev"
];
$anyAdamCameron = [
"firstName" => "Adam",
"lastName" => "Cameron"
];
echo haystackContainsNeedle($haystack, $anyAdamCameron) . PHP_EOL; // true
$anyAdam = [
"firstName" => "Adam"
];
echo haystackContainsNeedle($haystack, $anyAdam) . PHP_EOL; // true
$someOtherCameron = [
"firstName" => "Donald",
"lastName" => "Cameron"
];
echo haystackContainsNeedle($haystack, $someOtherCameron) . PHP_EOL; // false
$someOtherAdamCameron = [
"firstName" => "Adam",
"lastName" => "Cameron",
"role" => "Ficticious soap opera character" // false
];
echo haystackContainsNeedle($haystack, $someOtherAdamCameron) . PHP_EOL;
$orderCheck = [
"lastName" => "Cameron",
"firstName" => "Adam"
];
echo haystackContainsNeedle($haystack, $orderCheck) . PHP_EOL; // TRUE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment