Hi, I have a problem. This code is always returning 1 on $register_complete even when I leave the username field (in the form) empty. function register_user() { $register_complete = register_check_username(); if($register_complete) { echo "Testing..."; } else { echo "Please in all fields correctly."; } } function register_check_username() { if(!isset($_POST['username'])) { return "0"; } else { return "1"; } }
You're returning a string whose value just happens to be "0", as opposed to returning a true zero. Strange things happen when using strings to represent numbers and then trying to use them in if calls and so on. If you want to return zero (as a poor man's false), return zero: not a string that just has one character that happens to be the character for zero. Same goes for one. Anyway, firstly try changing your register_check_username function to something like: function register_check_username() { if(!isset($_POST['username'])) { return 0; } else { return 1; } } if that works, then in reality you should actually change it. You don't really want to return numbers, you want to return boolean values. function register_check_username() { if(!isset($_POST['username'])) { return false; } else { return true; } } This can even be made a lot simpler by: function register_check_username() { return isset($_POST['username']); }
TwistMyArm, I think you do not understand question correctly. He said "This code is always returning 1 on $register_complete even when I leave the username field (in the form) empty." There is no matter for PHP what to compare, it is always will be True: ("0" == false) (0 == false) ("1" == true) (1 == true) Vizuke, if you have a text field on the form, you always will have variable 'username' set. So you need to check is this variable empty or not. Your function can be as follows: function register_check_username() { if (isset($_POST['username']) && trim($_POST['username']) != '') return true; else return false; } PHP:
wmtips: you're absolutely correct. That's what I get for trying to answer forum questions when I've just woken up to feed the baby I would like to add, though, that my argument against returning numbers as strings still stands.
TwistMyArm, no problems . About returning numbers: sure they are better than strings in such case. But I prefer bool for logical functions (yes/no), boolean results are easy to understand. Also we can do our functions or conditions more elegant with booleans, for example: function register_check_username() { return (isset($_POST['username']) && trim($_POST['username']) != ''); } PHP:
Thanks for the tip guys. I fixed it with the empty() function. function register_check_username() { if(empty($_POST['username'])) { return 0; } else { return 1; } } PHP: [/php]