Skip to content

Instantly share code, notes, and snippets.

@KnightAlex
Created October 7, 2014 10:02
Show Gist options
  • Save KnightAlex/7661bd5bd36c5c158438 to your computer and use it in GitHub Desktop.
Save KnightAlex/7661bd5bd36c5c158438 to your computer and use it in GitHub Desktop.
PHP: Determine whether an object field matches needle.
<?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