Home › Forums › Add-ons › Repeater Field › Store subfield values in an array and check if a certain value exists
Hi there,
I have a repeater field with 2 sub fields (1 for title and 1 for description).
I basically want to look at the repeater rows and say “if one of the titles equals “this phrase”, then set a variable to true”.
To clarify, I don’t want to do this within the while loop.
I thought one way to do it would be to get all the subfield titles in an array, and then check to see if any of the array values match the phrase, but I can’t figure out how to do it!
Any help would be greatly appreciated!
Thank you
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
.
That is just the ticket – works a treat! Thanks so much for your help!
You must be logged in to reply to this topic.
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 Cookie Policy. If you continue to use this site, you consent to our use of cookies.