Skip to content

Instantly share code, notes, and snippets.

@dankerizer
Created February 24, 2020 16:45
Show Gist options
  • Save dankerizer/bbf2bb1244a1ab1c909d4837a8e84dc7 to your computer and use it in GitHub Desktop.
Save dankerizer/bbf2bb1244a1ab1c909d4837a8e84dc7 to your computer and use it in GitHub Desktop.
FInd In Array Value in Dimensional Object
<?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;
}
/**
Example
**/
$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.';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment