I have some simple code what gets user inserted parameters. But how can I use $_POST
to set a default value? For example, if a user is asked to input name and age and he chose to input only the name I need that $_POST
sets age to 0.
My code what I use:
$name = $_POST['name'];
$weight= $_POST['weight'];
$size = $_POST['size'];
And sometimes there can be only weight or size so I need to set up default value. I tried $size = $_POST['size'] ?? 0;
but it not worked.
You can use ternary operator to set default values for non-required fields.
$name = $_POST['name'];
$weight= (!empty($_POST['weight'])) ? $_POST['weight'] : 0;
$size = (!empty($_POST['size'])) ? $_POST['size'] : 0;
Reference:-
Note:- You can do same for name
also like:-
$name = (!empty($_POST['name'])) ? $_POST['name'] : '';
Remark:- Null coalescing operator ??
only worked in php 7+
The isset()
function is used to check whether a variable is set or not. If a variable is already unset with unset() function, it will no longer be set. The isset()
function return false if testing variable contains a NULL value.
Version: PHP 4 and above
Test Code :
$name = isset($_POST['name']) ? $_POST['name'] : '';
$weight= isset($_POST['weight']) ? $_POST['weight'] : 0;
$size = isset($_POST['size']) ? $_POST['size'] : 0;
Try :
$size = (isset($_POST['size'])) ? $_POST['size'] : 0;