Created
October 7, 2014 10:02
-
-
Save KnightAlex/7661bd5bd36c5c158438 to your computer and use it in GitHub Desktop.
PHP: Determine whether an object field matches needle.
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 | |
$arr = array( new stdClass(), new stdClass() ); | |
$arr[0]->colour = 'red'; | |
$arr[1]->colour = 'green'; | |
$arr[1]->state = 'enabled'; | |
if (in_array_field('red', 'colour', $arr)) | |
echo 'Item exists with colour red.'; | |
if (in_array_field('magenta', 'colour', $arr)) | |
echo 'Item exists with colour magenta.'; | |
if (in_array_field('enabled', 'state', $arr)) | |
echo 'Item exists with enabled state.'; | |
?> | |
Output: | |
-------- | |
Item exists with colour red. | |
Item exists with enabled state. | |
<?php | |
function in_array_field($needle, $needle_field, $haystack, $strict = false) { | |
if ($strict) { | |
foreach ($haystack as $item) | |
if (isset($item->$needle_field) && $item->$needle_field === $needle) | |
return true; | |
} | |
else { | |
foreach ($haystack as $item) | |
if (isset($item->$needle_field) && $item->$needle_field == $needle) | |
return true; | |
} | |
return false; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment