Created
February 24, 2020 16:45
-
-
Save dankerizer/bbf2bb1244a1ab1c909d4837a8e84dc7 to your computer and use it in GitHub Desktop.
FInd In Array Value in Dimensional Object
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 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