0

I have this data coming from $myoptions = my_get_option('my_repeat_group');

$p = 'T1X 0L6'; // find me

print_r($myoptions) =

Array ( [0] => Array ( 
[region_name] => Alberta 
[postal_codes] => T1X 0L3,T1X 0L4,T1X 0L5,T1X 0L6,T1X 0L7 
[region_discount] => .5 )
[1] => Array ( 
[region_name] => Ontario 
[postal_codes] => T1M 0W3,T1M 0W4,T1M 0W5,T1M 0W6,T1M 0W7 
[region_discount] => .25 ) )

foreach ( $myoptions as $key => $value ) {
   if ( in_array($p, $value['postal_codes'] ) {
      // need to know $key of which array the $p was found,
      // in this case, I would like to find [0]
   }
}

I would like to find $p within $value['postal_codes'], and when I do find it, return the key in which it came from.

1

$value['postal_codes'] is not an array it is a string, you either need to explode it like:

foreach ( $myoptions as $key => $value ) {
   if (in_array($p,explode(","$value['postal_codes']){
      // need to know $key of which array the $p was found, in this case I would like to find [0]
   }
}

Or search on the string

foreach ( $myoptions as $key => $value ) {
   if (strstr($value['postal_codes'],$p){

   }
}

Or the most efficient way would be use array_search on the exploded like so:

foreach($myoptions as $key => $options) {
   $keys_containing_p[$key] = array_search($p,explode(",",$options['postal_codes']));
}
  • Thanks @Liam! the most efficient way worked great! it is returning the $key I am looking for... solid! – Ray Flores Nov 22 '16 at 21:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.