Skip to content

Instantly share code, notes, and snippets.

@BurakBoz
Last active March 31, 2022 09:49
Show Gist options
  • Save BurakBoz/fd09170d751d36e7677a11ddd3272f3d to your computer and use it in GitHub Desktop.
Save BurakBoz/fd09170d751d36e7677a11ddd3272f3d to your computer and use it in GitHub Desktop.
PHP Helper Functions anyKeyValueOr
<?php
function anyKeyValueOr(array|object|null $haystack, array $acceptableKeys = [], $defaultValue = null)
{
if (is_null($haystack) or empty($acceptableKeys))
{
return $defaultValue;
}
$isObject = is_object($haystack);
$isArray = is_array($haystack);
foreach ($acceptableKeys as $key)
{
if($isObject && isset($haystack->{$key}))
{
return $haystack->{$key};
}
else if($isArray && isset($haystack[$key]))
{
return $haystack[$key];
}
}
return $defaultValue;
}
$testArray = ["a" => 1, "b" => 2, "c" => 3];
$testObject = (object)$testArray;
it("Should return false", anyKeyValueOr($testArray, ["z"], false) === false);
it("Should return null", anyKeyValueOr($testArray, ["z"]) === null);
it("Should return 1", anyKeyValueOr($testArray, ["a"]) === 1);
it("Should return false", anyKeyValueOr($testObject, ["z"], false) === false);
it("Should return null", anyKeyValueOr($testObject, ["z"]) === null);
it("Should return 1", anyKeyValueOr($testObject, ["a"]) === 1);
it("Should return true", anyKeyValueOr($testObject, [], true) === true);
function it(string $name, bool $bool)
{
echo $name . " : " . ($bool ? "OK" : "FAIL") . PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment