Get numeric suffix from key starting with specific substring
Asked Answered
D

8

47

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?

Decury answered 14/10, 2010 at 9:59 Comment(3)
Can you give an example?Toth
I have voted to close this question as Unclear. There is no sample array, no desired output, no coding attempt, no clear explanation of what is being done with the trailing portion of the qualifying key. I don't know if multiple keys may qualify. We simply don't have a minimal reproducible example here.Amble
This question is not ideal. My prior attempt to close this page aged away. There is no sample array, no desired output, no coding attempt, no clear explanation of what is being done with the trailing portion of the qualifying key. I don't know if multiple keys may qualify. We simply don't have a minimal reproducible example here.Amble
B
34

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...
  }
}
Buckjumper answered 14/10, 2010 at 10:3 Comment(1)
I considered this for what I'm working on but I suspect it'd be painfully slow on huge arrays.Pay
B
27

You can isolate the entire array's keys as a new array, then use a regular expression to filter the entire new array only keeping values which start with show_me_, then access the original array value which the first qualifying key holds.

$value = $my_array[current(preg_grep('/^show_me_/', array_keys($my_array)))];
Bailor answered 8/4, 2013 at 19:30 Comment(1)
This will not be the most efficient technique because preg_grep() will continue processing all elements even after the sought key is found.Amble
H
9

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

Hendecasyllable answered 14/10, 2010 at 10:8 Comment(2)
This works for me in my situation, though note that this line: if (strpos($k, 'show_me_') !== false) should be if (strpos($v, 'show_me_') !== false)Nosography
It would be more desirable to use 0 === strpos($k, 'show_me_') to ensure it is only the prefix that matches and values like noshow_me_ do not also matchGrowth
W
9

to search for certain string in array keys you can use array_filter(); see docs

// the array you'll search in
$array = ["search_1"=>"value1","search_2"=>"value2","not_search"=>"value3"];
// filter the array and assign the returned array to variable
$foo = array_filter(
    // the array you wanna search in
    $array, 
    // callback function to search for certain sting
    function ($key){ 
        return(strpos($key,'search_') !== false);
    }, 
    // flag to let the array_filter(); know that you deal with array keys
    ARRAY_FILTER_USE_KEY
);
// print out the returned array
print_r($foo);

if you search in the array values you can use the flag 0 or leave the flag empty

$foo = array_filter(
    // the array you wanna search in
    $array, 
    // callback function to search for certain sting
    function ($value){ 
        return(strpos($value,'value') !== false);
    }, 
    // flag to let the array_filter(); know that you deal with array value
    0
);

or

$foo = array_filter(
    // the array you wanna search in
    $array, 
    // callback function to search for certain sting
    function ($value){ 
        return(strpos($value,'value') !== false);
    }
);

if you search in the array values and array keys you can use the flag ARRAY_FILTER_USE_BOTH

$foo = array_filter(
    // the array you wanna search in
    $array, 
    // callback function to search for certain sting
    function ($value, $key){ 
        return(strpos($key,'search_') !== false or strpos($value,'value') !== false);
    },
    ARRAY_FILTER_USE_BOTH
);

in case you'll search for both you have to pass 2 arguments to the callback function

Wheedle answered 3/1, 2019 at 13:3 Comment(2)
What If I want to return the string value at the end of this logic? Because currently this is returning the key and the value within one arrayAuscultation
This will not be the most efficient technique because array_filter() will continue processing all elements even after the sought key is found.Amble
P
4

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";
        }
}
Pelting answered 14/10, 2010 at 10:12 Comment(1)
You might even use \K to avoid the capture group.Amble
A
0

Confirming that the qualifying key is found and extracting the numeric suffix can be achieved by only calling sscanf() inside a loop (instead of two or three function calls). The numeric suffix can even be cast as an integer by using %d in the format parameter.

When the sought key is found, break the loop because there is no point searching any longer. Other scripts which use array_filter(), preg_grep(), or an unbroken foreach() will unnecessarily and suboptimally iterate over the entire array -- even after the sought key is encountered.

Code: (Demo)

$array = [
    'foo' => 1,
    'show_me_120' => 'something',
    'bar' => 42,
];
$showMeNumber = null;
foreach ($array as $k => $v) {
    if (sscanf($k, 'show_me_%d', $showMeNumber)) {
        break;
    }
}
var_export($showMeNumber);
// 120
Amble answered 28/12, 2023 at 20:38 Comment(0)
P
-1
 foreach($myarray as $key=>$value)
    if(count(explode('show_me_',$event_key)) > 1){
         //if array key contains show_me_
    }

More information (example):

if array key contain 'show_me_'

$example = explode('show_me_','show_me_120');

print_r($example)

Array ( [0] => [1] => 120 ) 

print_r(count($example))

2 

print_r($example[1])

 120 
Pastypat answered 13/7, 2016 at 10:18 Comment(4)
Could you explain in more detail what this piece of code means?Gratification
if array key contain 'show_me_' $example = explode('show_me_','show_me_120'); $example is: Array ( [0] => [1] => 120 ) count($example) is: 2 $example[1] is: 120Pastypat
Why do you need two functions (explode and count), if you can use substring or strpos?Elative
@Vin why do you need two substring and strpos if you can use sscanf()?Amble
A
-1
filter_array(
    $array,
    function ($var) {
        return (strpos($var, 'searched_word') !== FALSE);
    },
);

return array 'searched_key' => 'value assigned to the key'
Anglofrench answered 17/12, 2018 at 17:33 Comment(3)
An unformatted blob of code with no context is usually not a good answer here. Maybe edit the Answer and make it clear what you are suggesting and why you think it answers the Question.Replication
How the developer will know these two variables: 'searched_key' & 'value assigned to the key' ?? Also this response is not well formattedAuscultation
That's invalid PHP syntax in several places.Packaging

© 2022 - 2024 — McMap. All rights reserved.