4

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.

4
  • 2
    The loop solution would be at most 3 lines - the for statement, the strpos check and a closing bracket. How more concise could it be? :) Commented Jan 17, 2013 at 9:11
  • what issues do you have with loop through the array and check the same and get the results ? Commented Jan 17, 2013 at 9:11
  • 1
    My Recommendation use array_walk function of php Commented Jan 17, 2013 at 9:12
  • @Laurent Yeah, that won't be but was curious if it could be solved in a more generic way. Like an extended version of in_array, with strpos'ing. Commented Jan 17, 2013 at 9:13

4 Answers 4

10
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);
Sign up to request clarification or add additional context in comments.

3 Comments

I know this can be done as pointed in my post, but anyway thanks :)
@Pushpesh I have edited my answer with another alternative. Please check.
@Pushpesh I have added demo link to the answer.
1
function returnkey($arr) {
    foreach($arr as $key => $val) {
        if(strpos($val, 'set-cookie') !== false) {
            return $key;
        }
    } 
    return false;
}

Comments

1

Hey there you can use array_walk function of php

Here is the detailed explanation.

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

Thanks.

Comments

0

A function to match $str in an array.

Use case: $key = strInArray ( 'set-cookie', $array );

function strInArray ( $str, $array ) {

    if ( array_walk ( $array, function ( $val, $key ) use ( &$data, $str ) {
        if ( strpos ( $val, $str ) !== false ) {
            $data = $key;
        }
    }));

    return $data;
}

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.