2 for循环嵌套并在一个内部基于外部选择

Aym*_*ein 0 php arrays

我有这些数组:

$payments = array(1=>'Cash',2=>Cheque,3=>credit,4=>other);
$selected = array(2,1);

foreach($payments as $key=>$value) {
   foreach($selected as $id) {
      if ($key == $id) {
         echo $id . "is selected" . '<br>';
      }
      else{
          echo $id . " is not selected" . '<br>';
      }
   }
}

 what expected:
 1 is selected
 2 is not selected
 3 is not selected
 4 is selected

 but i got:
 1 is not selected
 1 is selected
 2 is selected
 2 is not selected
 3 is not selected
 3 is not selected
 4 is not selected
 4 is not selected
Run Code Online (Sandbox Code Playgroud)

我的循环中有什么问题?

u_m*_*der 5

你不需要内循环:

$payments = array(1=>'Cash',2=>Cheque,3=>credit,4=>other);
$selected = array(2,1);

foreach($payments as $key=>$value) {
  if (in_array($key, $selected)( {
     echo $key . "is selected" . '<br>';
  } else {
      echo $key . " is not selected" . '<br>';
  }
}
Run Code Online (Sandbox Code Playgroud)