【问题标题】:Adding values to an array from an included functions file in PHP从 PHP 中包含的函数文件向数组添加值
【发布时间】:2016-08-11 00:35:03
【问题描述】:

我是 PHP 编程新手,我需要帮助解决我确定的一个简单问题。我正在尝试将值添加到表单页面中称为错误的数组中,这样我可以稍后将其回显以进行验证,尽管我似乎无法从包含的函数文件中向数组中添加任何内容。

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

然后我创建数组<?php $errors = array(); ?>

然后我从包含<?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>";
        }
        ?>

但最终没有任何回声,提前感谢您的帮助

【问题讨论】:

  • 我不能将值返回到数组中吗?还是我需要返回一个普通变量,然后将其添加到我的测试文件中的数组中?
  • 你的数组不在函数范围内。阅读上面的链接问题。

标签: php arrays function include


【解决方案1】:

功能就像围墙花园 - 您可以进出,但是当您在里面时,您看不到墙外的任何人。为了与其余代码进行交互,您必须将结果传回,通过引用传入变量,或者(最坏的方式)使用全局变量。

您可以将 $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;
} 

【讨论】:

  • 非常感谢,一直卡在这个问题上,现在我终于可以继续前进了。
【解决方案2】:

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>";
    }
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 2016-03-08
    • 2017-09-08
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    • 2015-08-02
    相关资源
    最近更新 更多