0

I've searched Google and the PHP docs but have yet to find a solution for this. E.g. supposing I want to perform a strstr() on all the keys of an array to determine for which keys are closest to what I'm searching for, such that:

for($i=0;$i<count($array);$i++) {
   if(@strstr(key($array[$i]), "$search")) {
     print "Found: ". key($array[$i]). "<br>";
   }
 }

"key($array[$i])" is a placeholder for whatever function or means required for selecting array keys as elements to perform a strstr() upon.

Any help is appreciated sincerely.

4 Answers 4

2

Use foreach to iterate through Key,Value Pair.

foreach($array as $key=>$value) {
   if(@strstr($key, "$search")) {
     print "Found: ". $key. "<br>";
   }
 }

More reference: http://php.net/manual/en/control-structures.foreach.php

Update to answer comment:

you can use

array_keys — Return all the keys or a subset of the keys of an array

http://php.net/manual/en/function.array-keys.php

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Of curiosity though, is there a way to accomplish this via a for loop instead?
1
foreach ($array as $key => $value)
{
    if(strstr($key, $search))
    {
         print "Found: ". $key. "<br>";
    }
}

Comments

1

This will do it...

$found = array_filter(
                     array_keys($array), 
                     function($key) use ($search) {
                         return strpos($key, $search) !== FALSE;
                     });

CodePad.

$found will be an array of all keys which included a substring of which is contained in $search.

If you are merely looking for the presence of a string inside of another, use strpos().

Comments

0

Another option is to pull out the desired keys in one step, e.g. using preg_grep().

$keys = preg_grep('/'.preg_quote($search, '/').'/', array_keys($array));

foreach ($keys as $key) {
    echo "Found $key<br>";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.