-1

複数のフィールドを持つフォームが正しく入力されているかどうかを確認するための次のコードがあります。問題は、文字列を適切に連結しないことです。

以下はコードの一部です。

if(strlen($name) < 2 || strlen($email) < 6 || strlen($subject) < 5 || strlen($message) < 15){
                $alert = "There are some problems: \n";

                if(strlen($name) < 2){
                    $alert . "Name is too short \n";
                }

                if(strlen($email) < 6){ 
                    $alert . "email is too short \n";
                }

                if(strlen($subject) < 5){
                    $alert . "The subject is too short \n";
                }

                if(strlen($message) < 15){ 
                    $alert . "Your message is too short \n";
                }

                $alert . "Please fill in te fields correctly";

                echo $alert;
                ?>
                <script>
                alert("<?= $alert ?>");
                </script>
                <?php
            }
            else { ... } ?>

各ifステートメント内にエコーを配置すると、それがトリガーされることが示されますが、最終的にエコーによってアラートが表示され、出力されるのは「いくつかの問題があります:」
アラート文字列が適切に連結されないのはなぜですか? 各文の \n を削除しようとしましたが、それもうまくいきませんでした。

4

2 に答える 2

0

そのような変数を連結することはできません。.=

.左右の引数を連結します。.=右側の引数を左側の引数に追加します。

if(strlen($name) < 2 || strlen($email) < 6 || strlen($subject) < 5 || strlen($message) < 15){
            $alert = "There are some problems: \n";

            if(strlen($name) < 2){
                $alert .= "Name is too short \n";
            }

            if(strlen($email) < 6){ 
                $alert .= "email is too short \n";
            }

            if(strlen($subject) < 5){
                $alert .= "The subject is too short \n";
            }

            if(strlen($message) < 15){ 
                $alert .= "Your message is too short \n";
            }

            $alert .= "Please fill in te fields correctly";

            echo $alert;
            ?>
            <script>
            alert("<?= $alert ?>");
            </script>
            <?php
        }
        else { ... } ?>
于 2012-06-12T11:51:39.047 に答える