views:

44

answers:

3

Hello there,

I have an array and in that array I have an array key that looks like, show_me_160 this array key may change a little, so sometimes the page may load and the array key maybe show_me_120, I want to now is possible to just string match the array key up until the last _ so that I can check what the value is after the last underscore?

+3  A: 

one solution i can think of:

foreach($myarray as $key=>$value){
  if("show_me_" == substr($key,0,8)){
    $number = substr($key,strrpos($key,'_'));
    // do whatever you need to with $number...
  }
}
oezi
A: 

you would have to iterate over your array to check each key separately, since you don't have the possibility to query the array directly (I'm assuming the array also holds totally unrelated keys, but you can skip the if part if that's not the case):

foreach($array as $k => $v)
{
  if (strpos($k, 'show_me_') !== false)
  {
    $number = substr($k, strrpos($k, '_'));
  }
}

However, this sounds like a very strange way of storing data, and if I were you, I'd check if there's not an other way (more efficient) of passing data around in your application ;)

Geoffrey Bachelet
+2  A: 

You can also use a preg_match based solution:

foreach($array as $str) {
        if(preg_match('/^show_me_(\d+)$/',$str,$m)) {
                echo "Array element ",$str," matched and number = ",$m[1],"\n";
        }
}
codaddict