selecting an array key based on partial string selecting an array key based on partial string php php

selecting an array key based on partial string


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...  }}


I ran into a similar problem recently. This is what I came up with:

$value = $my_array[current(preg_grep('/^show_me_/', array_keys($my_array)))];


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 ;)