簡體   English   中英

從PHP中包含的函數文件向數組添加值

[英]Adding values to an array from an included functions file in PHP

我是PHP編程的新手,我肯定需要幫助一個簡單的問題。 我試圖在表單頁面中將值添加到稱為錯誤的數組中,這樣我以后就可以對其進行回顯以進行驗證,盡管我似乎無法從包含的函數文件中向數組中添加任何內容。

我需要函數<?php require_once("functions.php") ?>

然后創建數組<?php $errors = array(); ?> <?php $errors = array(); ?>

然后,我從include <?php minLength($test, 20); ?>調用該函數<?php minLength($test, 20); ?> <?php minLength($test, 20); ?>

在這里起作用

function minLength($input, $min) { if (strlen($input) <= $min) { return $errors[] = "Is that your real name? No its not."; } else { return $errors[] = ""; } }

然后在最后回聲他們,像這樣

<?php 
        if (isset($errors)) {
            foreach($errors as $error) {
    echo "<li>{$error}</li><br />";
        } 
        } else {
            echo "<p>No errors found </p>";
        }
        ?>

但最后沒有回音,在此先感謝您的幫助

minLength()函數返回您定義的$errors 但是,您的代碼中沒有$errors接受該函數的返回。

示例代碼為:

<?php
    require_once("functions.php");
    $errors = array();

    $errors = minLength($test, 20);

    if (count($errors) > 0) {
        foreach($errors as $error) {
            echo "<li>{$error}</li><br />";
        } 
    } else {
        echo "<p>No errors found </p>";
    }
?>

功能就像有圍牆的花園-您可以進入和退出,但是當您進入室內時,看不到任何在牆外的人。 為了與其余代碼交互,您要么必須將結果傳遞回去,要么按引用傳遞變量,要么(最糟糕的方式)使用全局變量。

您可以將$ errors數組聲明為函數內部的全局變量,然后對其進行更改。 這種方法不需要我們從函數返回任何東西。

function minLength($input, $min) {
    global $errors;
    if (strlen($input) <= $min) {
        //this syntax adds a new element to an array
        $errors[] = "Is that your real name? No its not.";
    } 
    //else not needed. if input is correct, do nothing...
}

您可以通過引用傳遞$ errors數組。 這是允許在函數內部更改全局聲明的變量的另一種方法。 我建議這樣。

function minLength($input, $min, &$errors) { //notice the &
    if (strlen($input) <= $min) {
        $errors[] = "Is that your real name? No its not.";
    } 
}
//Then the function call changes to:
minLength($test, 20, $errors); 

但是為了完整起見,這是使用返回值來實現的方法。 這很棘手,因為無論輸入是否錯誤,它都會添加一個新的數組元素。 我們真的不想要一個充滿空錯誤的數組,這沒有任何意義。 它們不是錯誤,因此它不應返回任何內容。 為了解決這個問題,我們重寫了該函數以返回字符串或布爾值false,然后在返回時測試該值:

function minLength($input, $min) {
    if (strlen($input) <= $min) {
        return "Is that your real name? No it's not.";
    } else {
        return false;
    }
}

//meanwhile, in the larger script...
//we need a variable here to 'catch' the returned value of the function
$result = minLength("12345678901234", 12);
if($result){ //if it has a value other than false, add a new error
    $errors[] = $result;
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM