0

I'm trying to find a way to check if the value of a given key exists in an array (inside a foreach loop).

For some reason it doesn't really work as expected.

The idea is that I already know the name of the key, but only know part of the correlating value for the key.

I'm trying to do something like this, assuming that I know the key is "exampleKeyName" and its value may or may-not contain "matchValue":

foreach( $array as $key => $value) {
  if (stripos($array["exampleKeyName"], 'matchValue') !== false) { echo "matched"; }
}

This returns "illegal string offset".

However, if I do this it works:

foreach( $array as $key => $value) {
  if (stripos($value, 'matchValue') !== false) { echo "matched"; }
}

The problem here is that I want to be more specific with the query, and only check if the key is "exampleKeyName".

user3143218
  • 1,738
  • 5
  • 32
  • 48

3 Answers3

1

You can use stripos to check the array value contains in a matching string like this way:

foreach( $array as $key => $value) {
  if (stripos($array[$key], 'matchValue') !== false) { echo "matched"; }
}
fortune
  • 3,361
  • 1
  • 20
  • 30
0

If you want to check if your regex pattern matches a specific value in your array :

if(preg_match("/^yourpattern$/",$myArray["exampleKeyName"])>0) {
    // The value of $myArray["exampleKeyName"] is matched by the regex
}

If you check if the regex matches a key :

foreach($myArray as $key => $value):
    if(preg_match("/^yourpattern$/",$key)>0) {
        // $key is matched by the regex
    }
endforeach;

I hope it helps !

edit : bad english

Camille Hodoul
  • 376
  • 2
  • 13
0

You're not far off, and there are a few ways of doing this.

In your example code you weren't checking the key but the value in both cases. When doing a for loop like in your second code example you have to change your if statement like so to check against the key:

if (stripos($key, 'matchValue') !== false) { echo "matched"; }

Since I don't know what the application of this is I'll just tell you a few other ways of achieving this and perhaps they will also help simplify the code.

php has a helper function called array_key_exists that checks if the given key or index exists in the array. The result is a boolean value. If you just need to know if the array contains an index or key that is another way of doing this. That would look like this:

if( array_key_exists('matchValue', $array) ) { 
    print('Key exists');
} else {
    print('No key found');
}

There is a good Stack Overflow posting about using preg_grep for regex searching of array keys that may also be helpful if you need to use regular expressions for this.

Community
  • 1
  • 1
Liam
  • 1,712
  • 1
  • 17
  • 30