-1

I want to get Array index with a particular Substring.

Here is what I got so far:

<?php
    $array = array(0 => 'blau', 1 => 'rot', 2 => 'grün', 3 => 'rot');
    $key = array_search('grün', $array);  // $key = 2;
    $key = array_search('rot', $array);   // $key = 1;
?>

It matches for the whole value. But, I want to match a substring. Is there a predefined function to achieve this goal?

Jenz
  • 8,280
  • 7
  • 44
  • 77

2 Answers2

-1

You could try to use array_filter with strpos

function search($var)
{
    if(strpos($var, 'some_sub_string') !== FALSE){
        return true;
    }

    return false;
}

$array = array(0 => 'blau', 1 => 'rot', 2 => 'grün', 3 => 'rot');
array_filter($array, 'search'));
alex
  • 602
  • 4
  • 7
-1
function array_substr_search($search, $array){
    foreach($array as $index => $value){
        if (stripos($value, $search) !== false){
            return $index;
        }
    }
}

$a = array('blue', 'red', 'yellow', 'purple');

print array_substr_search('ello', $a); //returns 2 (yellow)
felipsmartins
  • 13,269
  • 4
  • 48
  • 56