Php - search for keys in an array that matches the pattern

I have an array that looks like this:

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

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

I was thinking about using a regex with a pattern like:

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

and then loop through the array and validate each key. (by the way, for demonstration purposes only, the $ prefix was hardcoded to 2, but in the real system this value is provided by the user).

I am wondering if there is an easier way to do this?

Thanks.

+13
source share
6 answers

you can just iterate over 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 template as a parameter

+14
source

I think you need something like this:

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

The result will be an array containing all the keys matching the regular expression. The keys can be used to get the corresponding value.

Take a look at the preg_grep function.

+38
source

Old question, but here is what I like to do:

 $array = [ '2.5' => 'ABDE', '4.8' => 'Some other value' ]; 

preg_grep + array_keys will find all the keys

 $keys = preg_grep( '/^2\.\d/i', array_keys( $array ) ); 

You can add array_intersect_key and array_flip to extract an array fragment matching the pattern

 $vals = array_intersect_key( $array, array_flip( preg_grep( '/^2\.\d/i', array_keys( $array ) ) ) ); 
+8
source

These are my ways

 $data = ["path"=>"folder","filename"=>"folder/file.txt","required"=>false]; // FIRST WAY $keys = array_keys($data); if (!in_array("path", $keys) && !in_array("filename",$keys) && !in_array("required",$keys)) { return myReturn(false, "Dados pendentes"); } // SECOND WAY $keys = implode("," array_keys($data)); if (!preg_match('/(path)|(filename)|(required)/'), $keys) { return myReturn(false, "Dados pendentes"); } 
+1
source

To get only part of the array with the corresponding keys, you can also write

 $matching_array = array_flip(preg_grep($pattern, array_flip($your_array))); 

This can lead to performance problems if your array gets too large.

0
source

For future programmers who are facing the same problem. Here is a more complete solution that does not use loops.

  $array = ['2.5'=> 'ABCDE', '2.9'=>'QWERTY']; $keys = array_keys($array); $matchingKeys = preg_grep('/^2\.+/', $keys); $filteredArray = array_intersect_key($array, array_flip($matchingKeys)); print_r($filteredArray); 
0
source

Source: https://habr.com/ru/post/925693/


All Articles