4

I have an array that contains a list of items and descriptions about those items. I'm trying to set up a script that will search every value for a partial string and return the key in which the value was found. Here's an example of the array.

Array
(
[10023] => Array
    (
        [0] => 10023
        [idTag] => 10023
        [1] => Bolt 4in full thread (252668)
        [desc] => Bolt 4in full thread (252668)
        [2] => PL9811
        [serialNo] => PL9811 
        [3] => 252-668
        [modelNo] => 252-668
    )
[10024] => Array
    (
        [0] => 10024
        [idTag] => 10024
        [1] => Bolt 6in full thread (252-670)
        [desc] => Bolt 6in full thread (252-670)
        [2] => PL9823
        [serialNo] => PL9823 
        [3] => 
        [modelNo] =>
    )

[91143] => Array
    (
        [0] => 91143
        [idTag] => 91143
        [1] => PEG 2.5mm SS (0711P)
        [desc] => PEG 2.5mm SS (0711P)
        [2] => PX3501
        [serialNo] => PX3501 
        [3] => 0711P
        [modelNo] => 0711P
    )

)

So if I were to search for '252-' I need the script to check all keys (idtag, desc, serialNo, and modelNo) for this value. Then return to me keys 10023 and 10024.

The script I'm currently using is:

function searchFor($haystack, $needle)
{
   foreach($haystack as $key => $value)
   {
      if ($value === $needle )
         return $key;
   }
   return false;
}

As it is currently, it does not work. however were I to change

if ($value['modelNo'] === $needle)

and search only the model number for exact matches (i.e. my search was 225-668 instead of just 225-) then it does indeed return key 10023.

As you can see - there are inconsistencies in the array data (such is the birth of this script) so I need to be able to search every possible key that may contain a value and receive the parent key.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
ak.image
  • 55
  • 5

1 Answers1

3

foreach again inside the existing foreach and use strpos() !== false to check for the $needle or false for not found:

foreach($haystack as $key => $array) {
  foreach($array as $value) {
      if(strpos($value, $needle) !== false) {
         return $key;
      }
  }
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87