Home › Forums › Add-ons › Repeater Field › Store subfield values in an array and check if a certain value exists › Reply To: Store subfield values in an array and check if a certain value exists
I have this little function to search through an object or array:
/**
* Search for a value in a multidimensional array or object
*
* @param $needle What to search for
* @param $haystack The array to search in
* @param bool $strict Strict mode
* @param $needle_field The field name to search in
* @return bool
*
* @author Pascal Jordin
*/
function search_recursive($needle, $haystack, $strict = false, $needle_field = false){
if ($needle_field) {
if (is_array($haystack)){
foreach ($haystack as $item) {
if (isset($item[$needle_field]) && ($strict ? $item[$needle_field] === $needle : $item[$needle_field] == $needle) || ((is_object($item) || is_array($item)) && search_recursive($needle, $item, $strict, $needle_field))) {
return true;
}
}
} elseif (is_object($haystack)){
foreach ($haystack as $item) {
if (isset($item->$needle_field) && ($strict ? $item->$needle_field === $needle : $item->$needle_field == $needle) || ((is_object($item) || is_array($item)) && search_recursive($needle, $item, $strict, $needle_field))) {
return true;
}
}
}
} else {
if (is_array($haystack) || is_object($haystack) || $haystack instanceof Traversable) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || ((is_object($item) || is_array($item)) && search_recursive($needle, $item, $strict, $needle_field))) {
return true;
}
}
}
}
return false;
}
With this you could search for it like:
$field = get_field('repeater_field_name');
$match = search_recursive('the phrase', $field, false, 'title');
Then $match
is true
if phrase match value of any sub field named title
.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.