shiro
shiro

Reputation: 155

Laravel match string to array

I am trying to match values from a user's input ($index) to an existing array ($ppeWorn). A user can select more than one option. When I try to find out if there are keys of the user's input that match the $ppeWorn array, I get only the first item selected.

The value of dd($indexArray) is:

array:2 [
  0 => "1"
  1 => "2"
]

My code is as follows:

case 7:
                        $index = ($parts[6]) ;

                        $ppeWorn = [
                            'None',
                            'Gloves',
                            'Fabric mask',
                            'Surgical/Medical mask',
                            'N95 mask (or equivalent)',
                            'Face shield or goggles/protective glasses',
                            'Disposable gown',
                            'Waterproof apron',
                        ];

                        $indexArray = explode(',', $index ) ;
                        dd($indexArray); 
                                                              
                            foreach($indexArray as $value) {

                                if ($ppeWorn[$value]) {

                                    $session["ppes"] = $ppeWorn[$value];
        
                                    $this->setSession($session);
        
                                    dd($session);
        
                                    $response = $this->sessionOpeningTag . "Have you received IPC training?\n1. Yes\n2. No";
                                
                                } else {

                                    $response = $this->sessionClosingTag . "You have entered an invalid answer";
        
                                    $this->deleteSession($session);
        
                                }  
                                 
                            }
                        
                        break;

Upvotes: 0

Views: 1089

Answers (2)

Gabrielle-M
Gabrielle-M

Reputation: 1077

You can check exists values from a users input($index) to an existing array($ppeWorn). By using this way ___

$checkValue = array_key_exists($users_input,$ppeWorn);
echo $checkValue;

returns true if the key exists in $ppeWorn;

Upvotes: 0

Rafik Farhad
Rafik Farhad

Reputation: 1202

So your $input is an array, but it's first element is "1,2". So as my understanding of your question and code (please update the code, provide only useful stuffs), you want to iterate over $index and match the values with switch-case.

To do this you may try:

$indexArray = explode(',', $index[0]; // cause $index[0] has a string which has 
                                      // some comma separated value

foreach($indexArray as $value) {
    ... ... ...
    // Do your stuffs here

}

Upvotes: 1

Related Questions