Search code examples
phparrayspartial-matches

Check if one of multiple values exists in array as a partial string match


For array with single values like

array(2) {
  ["blue"]=>
  int(0)
  ["red"]=>
  int(1)
}

I use this code

<?php
if (array_key_exists('blue',$array))
{
    echo "jo";
}
?>

But what code do I need to use for arrays like this

array(2) {
  ["yellow blue"]=>
  int(0)
  ["red white"]=>
  int(1)
}

to check if blue exists?


Solution

  • My take:

    if(preg_grep('/blue/', array_keys($array))) { echo 'found'; }
    

    Or if you want to get them:

    $matches = preg_grep('/blue/', array_keys($array));
    print_r($matches);