1

I am wondering whether it is possible to use a variable inside of the same if statement that it is assigned in using PHP.

For example:

if ($start = strtotime($_POST['date']) && $start <= time()) {
    $error = 'You must choose a date in the future.';
}

That code does not appear to be working for me, but I don't see why it shouldn't since I know the variable can be assigned like that, and it would make sense for me for the following variable to then be able to access it.

5
  • Answer -> stackoverflow.com/questions/16092730/… Commented Feb 13, 2018 at 5:03
  • Possible duplicate of Set variable in if statement expression Commented Feb 13, 2018 at 5:04
  • In what way isn't it working? Are you getting an error? Commented Feb 13, 2018 at 5:06
  • @JDSchenck that thread does not address whether or not I can use the assigned variable in the same statement Commented Feb 13, 2018 at 5:06
  • @Barmer, when i post a date in the future, the statement returns "You must choose...". Please see eval.in/955103. Commented Feb 13, 2018 at 5:07

1 Answer 1

8

You're running into operator precedence problems. && has higher precedence than =, so it's being processed as:

if ($start = (strtotime($_POST['date']) && $start <= time())) {

This doesn't assign to $start until after the && expression completes, which means it will try to use $start in the comparison before it has been assigned. And it also assigns a boolean true/false value to $start, which is obviously not useful.

Either put parentheses around the assignment, or use the lower precedence and operator:

if (($start = strtotime($_POST['date'])) && $start <= time()) {

if ($start = strtotime($_POST['date']) and $start <= time()) {
Sign up to request clarification or add additional context in comments.

1 Comment

@AlivetoDie This answer addressed the problem exactly. The problem was the higher order of &&, if you want to see an example of the problem, see here: eval.in/955110.

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.