4

This can be done in Javascript with isNAN instead of !isset. Using the example below - both forms post to my script, one without a value and one with a value. Is the below code a correct way to do this in PHP to assign a value if the post var is not present?

$mycheck = !isset($_POST['value']) ? 0 : $_POST['value'];

<? 
if($_POST) :
  $mycheck = !isset($_POST['value']) ? 0 : $_POST['value'];
  echo $mycheck;
endif;
?>

<!-- send value-->
<form action="" method="post">
  <select name="value">
    <option value="0">0</option>
    <option value="5">5</option>
  </select>
  <input type="submit" name="submit">
</form>

<!-- doesn't send value-->
<form action="" method="post">
  <input name="different_var">
  <input type="submit" name="submit">
</form>
1

2 Answers 2

6

Yes, that's an acceptable way of setting default values.

An alternative, introduced in PHP 5.3, is to omit the middle argument of your ternary expression:

$mycheck = $_POST['value'] ?: 0;

However, this will likely throw notices for trying to access an array with a non-existant key if $_POST['value'] isn't set. Therefore your original method is more-accepted.

Sign up to request clarification or add additional context in comments.

7 Comments

It should be $_POST['value'] instead of isset($_POST['value']), as per the OP's intentions.
I think that isset() is perfectly acceptable for this solution. It will always give true or false, and will do exactly what the OP wants...
so if the posted value is a string your method is acceptable, but if its an array its better to use my original method?
I would think so. Ternary operators are looking for a true/false response and isset() will always give you that, even with an array.
@Innate Sort of but not quite. It depends on whether the value is already defined (hence, if you had an undefined string $value, the abbreviated notation will still throw notices). However, notices are rarely ever worth paying attention to and almost certainly not worth writing longer code to avoid; a case of useless notices is where session_start() will throw notices at you if a session is already declared, even though you need session_start() on every page to extend the session.
|
1

It works, but there's a cleaner way of writing it.

As of PHP 5.3, you can shorten ternary operations down to two expressions, like so:

$mycheck = $_POST['value'] ?: 0;

It means basically what you already have.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.