Phear46 Posted April 28, 2013 Share Posted April 28, 2013 function validate() { //Returns 'false' with no errors //Returns 'true' with errors $ERROR_Validate = false; $ERROR_Specify = array(); foreach($_POST as $a) { if ($a == "") { $ERROR_Validate = true; array_push($ERROR_Specify, "$a is empty!"; } } if($ERROR_Validate == false) { return false; } else { return array($ERROR_Specify); } } OK all i want to do here is test for empty form inputs. its working fine. Then I wanted to make it report which inputs were missing and i cant quite figure out how. Above is what i had but I realise "array_push($ERROR_Specify, "$a is empty!";" is wrong. this will add > "is empty" < to the array. I need to figure out how to get the correct key from the $_POST array when the element is empty. Also, running this script results in a error and im not sure why. commenting out the array_push line fixes it. I dont understand why. Thanks for reading! Im still learning php so youll have to forgive me for some silly mistakes! Quote Link to comment Share on other sites More sharing options...
PaperTiger Posted April 28, 2013 Share Posted April 28, 2013 If you want to get the array key in your foreach, you can do: foreach($_POST as $key => $value) A few other notes: - Rather than just checking if the value = "", you may want to trim it first. As if someone enters a blank space I would assume you'd want that to return an error about being empty, but it wouldn't because " " != "". There is also a function in php called empty() which checks if a variable is "empty", though depending on the variable type it can produce unexpected results sometimes. - Where you're doing "return array($ERROR_Specify);", you have already said that $ERROR_Specify is an array, so you don't need to then put that array into another array unless you have some other reason for doing so. Quote Link to comment Share on other sites More sharing options...
Phear46 Posted April 28, 2013 Author Share Posted April 28, 2013 Thankyou PaperTiger, that worked perfectly! didnt know you could do that in a foreach! And yeah, return array($ERROR_Specify) was giving me a weird output. Ill have a look at empty(), ive played about with it but it can, like you say, throw weird results. I think im going to try and write my own function for testing inputs at somepoint, I want to make sure the strings arent to long or short and dont contain anything but (a-z 0-9) etc. ill get round to that later, this works for now! Thankyou! 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.