dongshu9458 2018-08-14 23:28
浏览 41

将错误消息存储在一个阵列中

I want to create a function that checks each filed, If empty add error messages for that field.

If I have the following form:

<form method="post">
    <input type="text" name="name" placeholder="Name">
    <input type="email" name="email" placeholder="Email">
    <input type="submit" name="submit" value="Submit">
</form>

I tried:

$errors = array();
function empty_check($var, $fieldName){
    if( empty($var) ){
        $error = $fieldName . ' can\'t be empty';
        array_push($errors, $error);
    }
}

if (isset($_POST['form_submit'])) {
    empty_check( $_POST['name'], 'Name' );
    empty_check( $_POST['email'], 'Email' );
    print_r($errors);
}

So if I submit the form and both fields are empty, I should get:

Array(
    [0] => Name can't be empty 
    [1] => Email can't be empty 
)

But I get error saying that the $errors inside empty_check function is not defined.

When I add it to the parameters:

function empty_check($var, $fieldName, $errors){
    ..
}

Then I need to add that parameter for each time I run the function, And I get an empty array:

empty_check( $_POST['name'], 'Name', $errors );
empty_check( $_POST['email'], 'Email', $errors );

That returns:

Array()

I tried return, But I get an error [] can't be used for reading:

function empty_check($var, $fieldName){
    if( empty($var) ){
        $errors[] = $fieldName . ' can\'t be empty';
        return $errors[];
    }
}

How should it be?

  • 写回答

3条回答 默认 最新

  • drm30963 2018-08-14 23:33
    关注

    Variables from the global scope must be declared with the global before use in a function scope. Reference: Variable scope.

    Therefore:

    function empty_check() {
      global $errors;
    
      // ..
    }
    

    This is similar to using the extern keyword to declare global variables in a function scope in C. This is different from many newer languages like JavaScript, whose functions can inherit variables from the global scope.

    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)