ArnisR Posted June 19, 2011 Report Share Posted June 19, 2011 Kā pārbaudīt visus caur HTML formu padotos POST mainīgos, lai nevajadzētu rakstīt katram mainīgajam savu pārbaudi, piemēram: if(empty($_POST["name"]) or empty($_POST["surname"]) or empty($_POST["email"]) ... ) { die("Nav aizpildīti visi formas lauki!"); } Quote Link to comment Share on other sites More sharing options...
daGrevis Posted June 19, 2011 Report Share Posted June 19, 2011 Nu $_POST ir masīvs, vai ne? Un lai masīvam izietu cauri? Pēc piecām minūtēm... Aizrāvos un uzrakstīju funkciju, kurai ir jānorāda parametrs, kam ir jābūt masīvam (asociatīvam, 1D). Funkcija atgriež "true", ja viss ir kārtībā (visi masīva elementi ir aizpildīti), bet "false", ja vismaz viens no tiem ir neaizpildīts. Piemērs: $_POST['email'] = ''; Kods ir tikai kā idejas demonstrēšana! function checkEmptiness( array $array ) { $errors = 0; forEach ( $array as $key => $value ) { if ( empty( $value ) ) { ++$errors; } } return ( ( $errors === 0 ) ? true : false ); } $testArray = array( 'x' => 1, 'y' => 3, 'z' => 23, //'q' => null ); var_dump( checkEmptiness( $testArray ) ); Quote Link to comment Share on other sites More sharing options...
briedis Posted June 19, 2011 Report Share Posted June 19, 2011 (edited) Bla bla, yep, yep Klau, šitais tev neliekas muļķīgi? :)) return $something ? true : false; EDIT, mana interpretācija par funkciju: <?php /** * Pārbaudam, vai nepieciešamās vērtības eksistē masīvā * @param array $arr Pārbaudāmais masīvs * @param array $required Masīvs ar indeksu nosaukumiem * @return bool */ function checkEmpty($arr, $required){ $arr = array_flip(array_filter($arr)); $tmp = array_intersect($arr, $required); return count($tmp) == count($required); } var_dump(checkEmpty(array("a" => "1", "b" => "2", "c" => "3", "d" => "4"), array("a", "b", "c", "d"))); //T var_dump(checkEmpty(array("a" => "1", "b" => "2", "c" => "3", "d" => ""), array("a", "b", "c", "d"))); //F var_dump(checkEmpty(array("a" => "1", "b" => "2", "c" => "3", "d" => ""), array("a", "b", "c"))); //T var_dump(checkEmpty(array("a" => "1", "b" => "2", "c" => "0"), array("a", "b", "c"))); //F, jo "0" ir empty var_dump(checkEmpty(array("a" => "1", "b" => "2", "c" => "0"), array("a", "b", "d"))); //F ?> Edited June 19, 2011 by briedis Quote Link to comment Share on other sites More sharing options...
daGrevis Posted June 19, 2011 Report Share Posted June 19, 2011 Klau, šitais tev neliekas muļķīgi? :)) return $something ? true : false; Es gribēju, lai atgriež "boolean". Es jau teicu, ka funkcija nav funkcijas vērta... tikai lai parādītu domu, lai autors saprastu "kā". Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.