Last active
March 31, 2022 09:49
-
-
Save BurakBoz/fd09170d751d36e7677a11ddd3272f3d to your computer and use it in GitHub Desktop.
PHP Helper Functions anyKeyValueOr
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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