Adding values to an array from an included functions file in PHP -


i new programming php , need i'm sure simple question. trying add values array called errors in form page way can echo out later verification, although cant seem add array included functions file.

i require functions <?php require_once("functions.php") ?>

then create array <?php $errors = array(); ?>

then call function includes <?php minlength($test, 20); ?>

function here

function minlength($input, $min) { if (strlen($input) <= $min) { return $errors[] = "is real name? no not."; } else { return $errors[] = ""; } }

then echo them out @ , @ end

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

but nothing echos in end, thank in advance help

functions walled gardens - can enter , exit, when you're inside, can't see outside walls. in order interact rest of code, either have pass result out, pass in variable reference, or (worst way) use global variable.

you declare $errors array global inside function, , alter it. approach not require return function.

function minlength($input, $min) {     global $errors;     if (strlen($input) <= $min) {         //this syntax adds new element array         $errors[] = "is real name? no not.";     }      //else not needed. if input correct, nothing... } 

you pass in $errors array reference. method allows globally declared variable altered while inside function. i'd recommend way.

function minlength($input, $min, &$errors) { //notice &     if (strlen($input) <= $min) {         $errors[] = "is real name? no not.";     }  } //then function call changes to: minlength($test, 20, $errors);  

but completeness, here's how return value. tricky, since add new array element whether input wrong or not. don't want array full of empty errors, makes no sense. aren't errors, shouldn't return anything. solve rewrite function return either string or boolean false, , test value when back:

function minlength($input, $min) {     if (strlen($input) <= $min) {         return "is real name? no it's not.";     } else {         return false;     } }  //meanwhile, in larger script... //we need variable here 'catch' returned value of function $result = minlength("12345678901234", 12); if($result){ //if has value other false, add new error     $errors[] = $result; }  

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -