I have the following PHP code:
$required_fields = array ('menu_name','visible','position');
foreach($required_fields as $fieldname)
{
if (!isset($_POST[$fieldname]) || empty($_POST[$fieldname]) )
{
$errors [] = $fieldname;
}
}
menu_name, visible and position are variables that are received through the post method.
When the value of visible is zero, it creates an entry into the error array.
What is the best way to detect if a variable is empty when 0 is considered “not empty”?
Since user data is sloppy, I use a custom function that treats empty spaces as non data. It sounds like this will do exactly what you want. This function will consider “0” to be valid (aka non-empty) data.
Please note it supports arrays too but requires that each value in the array contains data, which can be useful as you can just do something like this:
PS: keep in mind this function will fire off PHP warnings if the value isn’t set and there’s no easy way around that, but you should NOT have warnings enabled in production anyways.