Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
what data does $cat_check have .. give some example –  Feroz Akbar Jul 18 '14 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. –  AbraCadaver Jul 18 '14 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? –  Otanaught Jul 18 '14 at 15:31
    
Sorry I've updated my question. I had it backwards. Trigger ONLY if array does NOT include entry 'Events' specifically. –  Dave Rottino Jul 18 '14 at 15:37

3 Answers 3

up vote 1 down vote accepted

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
   }
}
share|improve this answer
    
That did it. Awesome. Thanks. –  Dave Rottino Jul 18 '14 at 15:48

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
}
share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.