否则,如果foreach不起作用

时间:2016-03-12 15:32:52

标签: php foreach

这个脚本使用else读取数组中的文本,如果它不起作用但如果我使用它是否有效我想使用其他如果有人可以建议如何做到这一点

if(isset($_REQUEST["maininput"])){
foreach($id as $uni){
    if (preg_match("/" . $uni . "/i", $_POST['maininput'])){
        $founda = $uni;
        $data = $uni . "\n";
        $fname = "accepted.txt";
        $file = fopen($fname, 'a');//creates new file
        fwrite($file, $data);
        fclose($file);
        break;
   }

}
}else if{
foreach($coures as $mac){
    if (preg_match("/" . $mac . "/i", $_POST['maininput'])){
        $found = $mac;
        $data = $mac;
        $fname = "accepted.txt";//generates random name
        $file = fopen($fname, 'a');//creates new file
        fwrite($file, $data);
        fclose($file);
        break;
    }

}
}else{
foreach($university as $un => $unis){
    if (preg_match("/" . $un . "/i", $_POST['maininput'])){
        $founde = $unis;
        //$data = serialize($unis);
        $fname = "accepted.txt";//generates random name
        file_put_contents($fname, $unis, FILE_APPEND);

        //$file = fopen($fname, 'a');//creates new file
        //fwrite($file, $data);
        //fclose($file);
        break;


    }
  }
}

1 个答案:

答案 0 :(得分:3)

语法错误

if(condition) {
  //magic
}
else if(other_condiotion) {
  //other magic
}
else {
 //no magic
}

或者您可以使用缩短版本:

$var = (condition) ? true : false;

http://php.net/manual/en/control-structures.elseif.php

编辑: 很难理解你的问题,但似乎你想这样做:

$found = null;
$founda = null;
if(isset($_REQUEST["maininput"])){
foreach($id as $uni){
    if (preg_match("/" . $uni . "/i", $_POST['maininput'])){
        $founda = $uni;
        $data = $uni . "\n";
        $fname = "accepted.txt";
        $file = fopen($fname, 'a');//creates new file
        fwrite($file, $data);
        fclose($file);
        break;
      }

   }
}
else {
    foreach($coures as $mac) {
    if (preg_match("/" . $mac . "/i", $_POST['maininput'])){
        $found = $mac;
        $data = $mac;
        $fname = "accepted.txt";//generates random name
        $file = fopen($fname, 'a');//creates new file
        fwrite($file, $data);
        fclose($file);
        break;
     }
  }
}

如果您没有提供额外的第二个条件来检查使用if(condition_match) {} else {//conditon doesn't match}

当您有2个或更多条件时,请使用else if进行检查:

$number = 3
if($number == 1) { //false
 //This is number 1
}
else if($number == 2) { //false
 //This is number 2
}
else { //true
 //This is number 3
}

现在很清楚了吗? 请检查此链接:http://php.net/manual/en/control-structures.elseif.php