1

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.

5
  • In what way didn't it work?
    – Nick
    Sep 17, 2018 at 10:16
  • 2
    ?? worked in php 7+
    – Mohammad
    Sep 17, 2018 at 10:19
  • It did not set any value. I have PHP 7.0.23
    – Thranduil
    Sep 17, 2018 at 10:21
  • I think you might need !empty($_POST['name']) Sep 17, 2018 at 10:24
  • Little offtopic, but - PHP's filter functions might be worth a look - php.net/manual/en/ref.filter.php Sep 17, 2018 at 10:37

3 Answers 3

5

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:-

empty()

Note:- You can do same for name also like:-

$name = (!empty($_POST['name'])) ? $_POST['name'] : '';

Remark:- Null coalescing operator ?? only worked in php 7+

1
  • 1
    Yes, it worked for me. Sorry, my fault I didn't see you use an !empty option.
    – Thranduil
    Sep 17, 2018 at 10:31
4

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;
0
0

Try :

$size = (isset($_POST['size'])) ? $_POST['size'] : 0;
2
  • When i was posting answer there was not answered by anyone. Sep 17, 2018 at 10:24
  • 3
    Regardless, while this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
    – Nic3500
    Sep 17, 2018 at 11:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.