39

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?

ralixyle
  • 754
  • 1
  • 7
  • 18

10 Answers10

40

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)
n a
  • 2,692
  • 8
  • 29
  • 39
34

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.

MartinNajemi
  • 514
  • 3
  • 18
smitrp
  • 1,292
  • 1
  • 12
  • 28
18

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

Quasdunk
  • 14,944
  • 3
  • 36
  • 45
6

PHP 5.3+

array_walk($arr, function($item, $key) {
    if(strpos($item, 'green') !== false) {
        echo 'Found in: ' . $item . ', with key: ' . $key;
    }
});
MrCode
  • 63,975
  • 10
  • 90
  • 112
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": ""
}
Kotzilla
  • 1,333
  • 18
  • 27
0
function check($string) 
{
    foreach($arr as $a) {
        if(strpos($a,$string) !== false) {
            return true;
        } 
    }
    return false;
}
Louis.CLast
  • 424
  • 1
  • 3
  • 15
0

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
}
phoenix
  • 1,629
  • 20
  • 11
  • Right! What i looked for. `if (preg_match('/my-word/sim', var_export($arr, true))) { /* match */ }else{ /* not match */ }` – Intacto Jan 10 '23 at 19:48
-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.

hirre
  • 19
  • 6
-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}
-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 :)

Oli Girling
  • 605
  • 8
  • 14