I have the following multiple checkbox selection:
Apple
Answer:
1. $_POST
array does not contain $_POST['fruit_list']
2. First answer is "No".A variable is considered empty if it does not exist or if its value equals FALSE. empty()
does not generate a warning if the variable does not exist.see in php.net
3. Empty checks if the variable is set and if it is it checks it for null, "", 0, etc.
Isset just checks if is it set, it could be anything not null. see
use print_r() to print the post data..
<?php
echo "<pre>"; print_r($_POST);
if (empty($_POST['fruit_list']) ){
echo "You must select at least one fruit.<br>";
}
else{
foreach ( $_POST['fruit_list'] as $frname ){
echo "Favourite fruit: $frname<br>";
}
}
?>
If you do not select any checkbox then you will not get $_POST['fruit_list'], array index fruit_list
does not exist in array
for difference between isset()
and empty()
Visit Here
$_POST['fruit_list']
No, key fruit_list does not exist
To check if key exists in array better use array_key_exists
because if you have NULL values isset
returns false
But in your case isset is a good way
isset
- Determine if a variable is set and is not NULL (have any value).
empty
- Determine whether a variable is empty (0, null, '', false, array()) but you can't understand if variable or key exists or not
For example:
$_POST['test'] = 0;
print 'isset check: ';
var_dump(isset($_POST['test']));
print 'empty check: ';
var_dump(empty($_POST['test']));
$_POST['test'] = null;
print 'isset NULL check: ';
var_dump(isset($_POST['test']));
print 'key exists NULL check: ';
var_dump(array_key_exists('test', $_POST));
isset check: bool(true)
empty check: bool(true)
isset NULL check: bool(false)
key exists NULL check: bool(true)