'Select cookie value based on string match

So I have this if statement where I am looking for a cookie:

if (isset($_COOKIE['OptanonConsent'])) {
   ...
}

Next, I'm breaking the cookie up using the explode function:

$cookie_array = explode("&", $_COOKIE['OptanonConsent']);

Which gives me the following output:

array(9) { 
   [0]=> string(26) "landingPath=NotLandingPage" 
   [1]=> string(67) "datestamp=Tue+Apr+12+2022+07:16:23+GMT-0500+(Central+Daylight+Time)" 
   [2]=> string(14) "version=6.33.0" 
   [3]=> string(30) "groups=C0001:1,C0002:0,C0004:0" 
   [4]=> string(6) "hosts=" 
   [5]=> string(14) "isGpcEnabled=0" 
   [6]=> string(13) "geolocation=;" 
   [7]=> string(17) "isIABGlobal=false" 
   [8]=> string(23) "AwaitingReconsent=false" 
}

Next, I want to filter through and just grab the array index that has "groups" in it, using the following:

$groups_array = array_filter($cookie_array, static function($value) {
    return str_contains($value, 'groups');
});

Which outputs:

array(1) { 
  [3]=> string(30) "groups=C0001:1,C0002:0,C0004:0" 
}

Next, I want to search and see if "C0004:0" exists, so I'm using:

$targeting_cookie_disabled = in_array('C0004:0', $groups_array, true);

But that is returning a false return. The index changes always, so I can't use $groups_array[3].


Does anyone know how to properly break up the cookie and grab just the "groups" index of an array and search through it?

php


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source