嵌套循环,如果PHP

时间:2014-02-12 07:08:50

标签: php

我尝试运行以下代码:

  • 1)我检查$ string_result的第一个字符
  • 2)如果$ string_result的第一个char在数组first_char中匹配,它将输出字符串结果
  • 3)如果第一个char等于“n”,我将$ string_result的前两个字符与数组second_char进行比较
  • 4)如果我删除嵌套的if n else,它运行良好。我在那里做了一些逻辑错误吗?

    <?php
        $string_result = "nyanyi";
        function awalan_pe($string_result){
        $first_char = array("m", "n", "r", "l", "w");
        $second_char = array("ny", "ng");
        $result = (substr($string_result, 0,2));
        foreach ($first_char as $value){
        if ($string_result[0] == $value) {
            $final_result = "pe".$string_result;
    
            if(($string_result[0] == $value) == "n"){
                foreach ($second_char as $value){
                    if($result == $value){
                    $final_result = "pe".$string_result;
                    }
                }
            }
        }
        else{
            return null;
        }
     }
    return $final_result;
    }
    echo awalan_pe($string_result);
    ?>
    

遗憾的是它返回null。

3 个答案:

答案 0 :(得分:1)

它将return null,因为您在找到正确的迭代后不会停止迭代。

在找到最终结果后移动返回$final_result,如

$final_result = "pe".$string_result;
return $final_result;

答案 1 :(得分:0)

in_array将在这种情况下提供帮助,请查看代码的自定义代码。

<?php
    $string_result = "nyanyi";
    function awalan_pe($string_result){
    $first_char = array("m", "n", "r", "l", "w");
    $second_char = array("ny", "ng");
    $result = (substr($string_result, 0,1)); //store 1st Char
    $result2 = (substr($string_result, 0,2)); //store 1st and 2nd Char
    $flag=0;
    if($result === "n") //if first char is "n"
    {
        if(in_array($result2, $second_char)) //to check whether entry is present in array or not
        {
            $final_result= "String Found";
            $flag=1;
        }
    }
    else{
        if(in_array($result, $first_char))
        {
            $final_result= "String Found";
            $flag=1;
        }
    }
    if($flag == 0)
    {
    return null;
    }

return $final_result;
}
echo awalan_pe($string_result);
?>

答案 2 :(得分:0)

按照你的方式,我修改了:

public function awalan_pe($string_result){
        $first_char = array("m", "n", "r", "l", "w");
        $second_char = array("ny", "ng");
        $str_len = strlen($string_result);
        for($i = 0; $i <= $str_len; $i++){
            foreach($first_char as $f_char){
                if(substr($string_result,$i,$i+1) == $f_char){
                    if(substr($string_result,$i,$i+1) == "n"){
                        for($j=0; $j <= $str_len; $j++){
                            foreach($second_char as $s_char){
                                if(substr($string_result,$i,$i+2) == $s_char){
                                    return "in second array value:" .$s_char;
                                }
                            }
                        }
                    }
                }
            }
        }
        return "not in first array";
    }