Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the values only if all the keys have matched?

I want to make a method that returns keys and values. But only if the keys include the following string "_1" and "__last".
If only one matches then exit the function, only if the two string are included in the key, return the key with the value for a weather.

$infoList = array("_key_1"=>array("time"=>9, "day"=>"Tuesday", "weather"=>"sunny", 
                                "humidity"=>"80%"),
                  "_key_2"=>array("time"=>5, "day"=>"Tuesday", "weather"=>"cloudy"),
                  "_key__last"=>array("time"=>3, "day"=>"Sunday", "weather"=>"rainy"))

public function getData() {
 $list = array();
 foreach($infoList as $key){
   if(preg_match('/(_key)_(_1)/', $key) && preg_match('/(_key)_(__last)/', $key) == TRUE){
     $list[$key] = $list[$key]["weather"] 
   } 

 }
 return $list

}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are making your life so much more difficult that it need be, use str_contains() its easier than building complex REGEX’s and getting very confused by the look of it 🙂

I also fixed a number of other mistakes, such as the foreach that was not going to work, so check all the code.
It is also better to pass data to a function/method otherwise you get into scoping issues!

$infoList = array("_key_1"=>array("time"=>9, "day"=>"Tuesday", "weather"=>"sunny", "humidity"=>"80%"),
                  "_key_2"=>array("time"=>5, "day"=>"Tuesday", "weather"=>"cloudy"),
                  "_key__last"=>array("time"=>3, "day"=>"Sunday", "weather"=>"rainy"));
                  
function getData(Array $infoList) {
    $list = [];
    $found = 0;
    foreach($infoList as $key => $val) {
        if( str_contains($key, '_1') || str_contains($key, '__last') ) {

            $list[$key] = $val["weather"];
            $found++;
        }
    }
    if ( $found >= 2 ) {
        return $list;
    } else {
        return false;
    }

}

$res = getData($infoList);
if ( $res !== false ){
    print_r($res);
} else {
    echo 'Not Found';
}

RESULTS

Array
(
    [_key_1] => sunny
    [_key__last] => rainy
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading