42

I have an array and I'd like to search for the string 'green'. So in this case it should return the $arr[2]

$arr = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');

is there any predefined function like in_array() that does the job rather than looping through it and compare each values?

2
  • what ? just use for loop on your array and compare values Commented Apr 11, 2013 at 9:12
  • yes it is, you can see in the answers below Commented Apr 11, 2013 at 9:13

10 Answers 10

44

For a partial match you can iterate the array and use a string search function like strpos().

function array_search_partial($arr, $keyword) {
    foreach($arr as $index => $string) {
        if (strpos($string, $keyword) !== FALSE)
            return $index;
    }
}

For an exact match, use in_array()

in_array('green', $arr)
Sign up to request clarification or add additional context in comments.

2 Comments

Don't forget the proper usage of strpos. if (strpos($string, 'green') !== FALSE)
The question clearly says looping is not an option cuz that would be too obvious
38

You can use preg_grep function of php. It's supported in PHP >= 4.0.5.

$array = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');
$m_array = preg_grep('/^green\s.*/', $array);

$m_array contains matched elements of array.

Comments

20

There are several ways...

$arr = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');

Search the array with a loop:

$results = array();

foreach ($arr as $value) {

  if (strpos($value, 'green') !== false) { $results[] = $value; }

}

if( empty($results) ) { echo 'No matches found.'; }
else { echo "'green' was found in: " . implode('; ', $results); }

Use array_filter():

$results = array_filter($arr, function($value) {
    return strpos($value, 'green') !== false;
});

In order to use Closures with other arguments there is the use-keyword. So you can abstract it and wrap it into a function:

function find_string_in_array ($arr, $string) {

    return array_filter($arr, function($value) use ($string) {
        return strpos($value, $string) !== false;
    });

}

$results = find_string_in_array ($arr, 'green');

if( empty($results) ) { echo 'No matches found.'; }
else { echo "'green' was found in: " . implode('; ', $results); }

Here's a working example: http://codepad.viper-7.com/xZtnN7

Comments

6

PHP 5.3+

array_walk($arr, function($item, $key) {
    if(strpos($item, 'green') !== false) {
        echo 'Found in: ' . $item . ', with key: ' . $key;
    }
});

Comments

3

for search with like as sql with '%needle%' you can try with

$input = preg_quote('gree', '~'); // don't forget to quote input string!
$data = array(
    1 => 'orange',
    2 => 'green string',
    3 => 'green', 
    4 => 'red', 
    5 => 'black'
    );
$result = preg_filter('~' . $input . '~', null, $data);

and result is

{
  "2": " string",
  "3": ""
}

Comments

1

A quick search for a phrase in the entire array might be something like this:

if (preg_match("/search/is", var_export($arr, true))) {
    // match
}

1 Comment

Right! What i looked for. if (preg_match('/my-word/sim', var_export($arr, true))) { /* match */ }else{ /* not match */ }
0
function check($string) 
{
    foreach($arr as $a) {
        if(strpos($a,$string) !== false) {
            return true;
        } 
    }
    return false;
}

1 Comment

The question clearly says looping is not an option.
-1
function findStr($arr, $str) 
{  
    foreach ($arr as &$s) 
    {
       if(strpos($s, $str) !== false)
           return $s;
    }

    return "";
}

You can change the return value to the corresponding index number with a little modification if you want, but since you said "...return the $arr[2]" I wrote it to return the value instead.

2 Comments

This won't work. strpos() never returns true, it only returns either an integer or false.
The question clearly says looping is not an option.
-1

In order to find out if UTF-8 case-insensitive substring is present in array, I found that this method would be much faster than using mb_strtolower or mb_convert_case:

  1. Implode the array into a string: $imploded=implode(" ", $myarray);.

  2. Convert imploded string to lowercase using custom function: $lowercased_imploded = to_lower_case($imploded);

    function to_lower_case($str) {

$from_array=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","Ä","Ö","Ü","Õ","Ž","Š"];

$to_array=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","ä","ö","ü","õ","ž","š"];

foreach($from_array as $key=>$val){$str=str_replace($val, $to_array[$key], $str);}

return $str;

}

  1. Search for match using ordinary strpos: if(strpos($lowercased_imploded, "substring_to_find")!==false){do something}

Comments

-1

This is a function for normal or multidimensional arrays.

  • Case in-sensitive
  • Works for normal arrays and multidimentional
  • Works when finding full or partial stings

Here's the code (version 1):

function array_find($needle, array $haystack, $column = null) {

    if(is_array($haystack[0]) === true) { // check for multidimentional array

        foreach (array_column($haystack, $column) as $key => $value) {
            if (strpos(strtolower($value), strtolower($needle)) !== false) {
                return $key;
            }
        }

    } else {
        foreach ($haystack as $key => $value) { // for normal array
            if (strpos(strtolower($value), strtolower($needle)) !== false) {
                return $key;
            }
        }
    }
    return false;
} 

Here is an example:

$multiArray = array(
     0 => array(
              'name' => 'kevin',
              'hobbies' => 'Football / Cricket'),
      1 => array(
              'name' => 'tom',
              'hobbies' => 'tennis'),
       2 => array(
              'name' => 'alex',
              'hobbies' => 'Golf, Softball')
);
$singleArray = array(
        0 => 'Tennis',
        1 => 'Cricket',
);

echo "key is - ". array_find('cricket', $singleArray); // returns - key is - 1
echo "key is - ". array_find('cricket', $multiArray, 'hobbies'); // returns - key is - 0 

For multidimensional arrays only - $column relates to the name of the key inside each array. If the $needle appeared more than once, I suggest adding onto this to add each key to an array.

Here is an example if you are expecting multiple matches (version 2):

function array_find($needle, array $haystack, $column = null) {

    $keyArray = array();

    if(is_array($haystack[0]) === true) { // for multidimentional array

        foreach (array_column($haystack, $column) as $key => $value) {
            if (strpos(strtolower($value), strtolower($needle)) !== false) {
                $keyArray[] = $key;

            }
        }

    } else {
        foreach ($haystack as $key => $value) { // for normal array
            if (strpos(strtolower($value), strtolower($needle)) !== false) {
                $keyArray[] = $key;
            }
        }
    }

    if(empty($keyArray)) {
        return false;
    }
    if(count($keyArray) == 1) {
        return $keyArray[0];
    } else {
        return $keyArray;
    }

}

This returns the key if it has just one match, but if there are multiple matches for the $needle inside any of the $column's then it will return an array of the matching keys.

Hope this helps :)

1 Comment

The question clearly says looping is not an option.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.