0

I have the following code that looks through the category array and finds the existence of the string 'Events'. I want only it to trigger if there is NOT an array entry called "Events", something like for example 'News and Events' is fine. I'm sure it's a simple solution but I can't seem to find it. Any thoughts?

$cat_check = get_the_category_list(',');

$cat_check_array = explode(",",$cat_check);

if(!(in_array("Events", $cat_check_array, true))) { 
    //Do Something
}

Example of categories in $cat_check

$cat_check = "News and Events","Category 1","Category 2";
$cat_check = "Events";

The only thing I don't want this bit of code to trigger on is the existence of an array entry "Events", anything else like "News and Events" is perfectly fine.

4
  • what data does $cat_check have .. give some example Commented Jul 18, 2014 at 15:30
  • You probably have it backwards with the !. It states IF Events is NOT in the array. If News and Events is in the array but not just Events then the IF is true. Commented Jul 18, 2014 at 15:31
  • "I want only it to trigger if the WHOLE array entry is Events" does this mean you want only to do something if all elements contain the word Events? Commented Jul 18, 2014 at 15:31
  • Sorry I've updated my question. I had it backwards. Trigger ONLY if array does NOT include entry 'Events' specifically. Commented Jul 18, 2014 at 15:37

3 Answers 3

1

in_array() does straight equality testing. It's not ever been capable of doing partial/substring matches. Bite the bullet and use a loop:

foreach($array as $haystack) {
   if (strpos($haystack, $needle) !== FALSE) {
      ... text is present
   }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Would array_reduce be what you are looking for?

function in_array_ext($value, $arr) {
   return array_reduce($arr, function ($carry, $item) use ($value) {
       return (strpos($item, $value) !== false) || $carry;
   }, false);
}


if (!in_array_ext("Events", $cat_check_array)) { 
   // Do something, "Events" does not present in the array values
}

Comments

0

You can easily perform that with the preg_grep function :

Return array entries that match the pattern

Code example :

$search = "Events"; // whatever you want
$result = preg_grep('~' . preg_quote($search, '~') . '~', $cat_check_array);

Here, we use the preg_quote function on the search variable to prevent uses of the ~ symbol

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.