0

I am trying to find a function which can find the index in an array, when I know just part of the string.
The function array_search returns me the index only in case I know whole string.
How do I get the index/key when I only have a substring of the array items?

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

echo array_search('red', $array);

I need to echo 1.

Andreas
  • 23,610
  • 6
  • 30
  • 62
Efritek
  • 13
  • 1

3 Answers3

1

Use foreach() to make an iteration over the array and strpos() for searching your needle in the elements of the array.

$array = [0 => 'blue pants', 1 => 'red pants', 2 => 'green pants', 3 => 'green pants'];

foreach ($array as $key => $value) {
    if (strpos($value, 'red') !== false) {
        echo "Key={$key}, Value: {$value}";
        break;
    }
}

Working demo.

MH2K9
  • 11,951
  • 7
  • 32
  • 49
0

I took this function from php.net from n-regen who find the value of array from a part of a needle. Then using the value found, you can get the value of the index using array_search.

function array_find($needle, $haystack)
{
   foreach ($haystack as $item)
   {
      if (strpos($item, $needle) !== FALSE)
      {
         return $item;
         break;
      }
   }
}


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


$completValue = array_find('red', $array);
echo array_search($completValue , $array);
Dylan KAS
  • 4,840
  • 2
  • 15
  • 33
0

You can also use preg_grep which is regex for arrays.
This will return all items that is red in your array.

And since it's regex, you can also set the pattern to not include "blue redneck pants", which strpos will have slightly more problem with.

$return = preg_grep("/red/", $array);

var_dump($return); 
/*
array(2) {
  [1]=>
  string(9) "red pants"
  [4]=>
  string(11) "red t-shirt"
}
*/

https://3v4l.org/IVUaJ

If you want to exclude the blue redneck pants then use the pattern /\bred\b/
https://3v4l.org/o9rGi

To make the pattern pick up "Red", "red", "RED", then use /\bred\b/i

Noticed you want the keys in return. Just do array_keys($return); and you will get the keys where "red" is mentioned.

Andreas
  • 23,610
  • 6
  • 30
  • 62