Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - finding keys in an array that match a pattern

Tags:

I have an array that looks like:

 Array ( [2.5] => ABDE [4.8] => Some other value )  

How would I find any key/value pair where the key matches a pattern? I will know the value of the first digit in the key,but not the second. so for example, using a prefix of "2.", I want to somehow be able to find the key "2.5" and return both the key and the value "ABDE".

I was thinking about using a regular expression with a pattern like:

$prefix = 2; $pattern = '/'.$prefix.'\.\d/i'; 

and then looping through the array and checking each key. (by the way, just for demo purposes, $prefix has been hardcoded to 2, but in the real system, this is a value provided by the user's input).

I'm wondering if there's a simpler way to do this?

Thanks.

like image 404
dot Avatar asked Sep 18 '12 17:09

dot


Video Answer


2 Answers

I think you need something like this:

$keys = array_keys($array); $result = preg_grep($pattern, $keys); 

The result will be a array that holds all the keys that match the regex. The keys can be used to retrieve the corresponding value.

Have a look at the preg_grep function.

like image 87
JvdBerg Avatar answered Sep 17 '22 01:09

JvdBerg


you can simply loop through the array and check the keys

$array = array(...your values...);  foreach($array as $key => $value) {     if (preg_match($pattern,$key)){         // it matches     } } 

You can wrap it in a function and pass your pattern as parameter

like image 36
Ibu Avatar answered Sep 21 '22 01:09

Ibu