Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for a part of string within an array

I want to check if a part of a string (not the full-string, as it will be variable) is present in an array.

$test = array(
  0 => 'my searcg',
  1 => 'set-cookie: shdugdd',
  2 => 'viable: dunno'
);

What i want is check if either of the keys has the string "set-cookie" and if so, return the key. I can't check for full string as the set-cookie value will differ every time. It might not be present as well, so need to check that as well.

I know i can loop through the array and check the same and get the results, but am looking for a more concise/efficient answer. Having trouble getting a solution.

like image 911
web-nomad Avatar asked Sep 06 '25 23:09

web-nomad


2 Answers

foreach($test as $key=> $value)
{
  if (strpos($value,'set-cookie') !== false) 
 {
  echo $key; // print key containing searched string
  }
}

Here is another alternative. (working example)

   $matches = preg_grep('/set-cookie/', $test); 
    $keys    = array_keys($matches); 

    print_r($matches);
like image 104
cartina Avatar answered Sep 08 '25 11:09

cartina


function returnkey($arr) {
    foreach($arr as $key => $val) {
        if(strpos($val, 'set-cookie') !== false) {
            return $key;
        }
    } 
    return false;
}
like image 34
Ms01 Avatar answered Sep 08 '25 13:09

Ms01