-1

I have an array like this:

[
  "customer" => 2325
  "product1" => 3,
  "product4" => 1,
  "product12" => 2
]

And I want to run a for-loop to find the keys that contain the word product and also get the number after the word. Is there any php function to find specific words inside a string?

Jonathan Solorzano
  • 6,812
  • 20
  • 70
  • 131
  • 1
    related: http://stackoverflow.com/questions/2471120/php-function-array-key-exists-and-regular-expressions – jeremy Aug 14 '16 at 20:28
  • `strpos` is this function – u_mulder Aug 14 '16 at 20:29
  • 2
    Possible duplicate of [Check if string contains specific words?](http://stackoverflow.com/questions/4366730/check-if-string-contains-specific-words) – pBuch Aug 14 '16 at 20:29
  • @feniixx you could probably refactor the code that produces this array to make this an lot easier task –  Aug 14 '16 at 20:49

1 Answers1

0

You could likely loop through your array while using stristr:

foreach($arr as $item => $val) { 
    $res[] = stristr($item, 'product');
    $int[] = filter_var($item, FILTER_SANITIZE_NUMBER_INT);
}
print_r(array_filter($res)); // output keys with substring 'product'
print_r(array_filter($int)); // output integers from product key substring

This would allow you to collect any keys that contain the sub-string 'product'. From there you could also capture any integers associated with that key.

Output:

Array
(
    [1] => product1
    [2] => product4
    [3] => product12
)
Array
(
    [1] => 1
    [2] => 4
    [3] => 12
)
l'L'l
  • 44,951
  • 10
  • 95
  • 146