Jump to content

Basic Question About Variable and If Statement

- - - - -

  • Please log in to reply
4 replies to this topic

#1
alexbeau

alexbeau

    Newbie

  • Members
  • Pip
  • 3 posts
I am a dead beginner with PHP and have been reading through 'PHP for the Web: Visual Quickstart Guide 4th Ed.' by Larry Ullman and have a question regarding something I came across in the book.

At the end of each chapter he has a few questions for review and I am stuck on one of them and not sure if I have the correct answer or the correct train of though regarding it.

The question is as follows:

Without knowing anything about $var will the following conditional be TRUE or FALSE? Why?

if ($var = 'donut') {...

I am apt to say that it will be false because we don't know if $var has been assigned the value donut yet within the program but I am not sure.

Can anyone help explain this to me so I can grasp this concept and feel confident about it?

Thank you,

Alex

#2
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,124 posts
  • Location:Vancouver, Eh! Cleverness: 200
Hello,

In this case the order of precedence applies, so 'donut' is assigned to $var, and then the statement becomes this:
if($var) {...

What will the statement become in this case assuming $var is not empty? Remember true does not explicitly have to be 1 or true, if the book has hinted at this before that should help you understand what it will be.

Alexander.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#3
alexbeau

alexbeau

    Newbie

  • Members
  • Pip
  • 3 posts
Ok the book mentioned precedence in respect to arithmetic operators but not in respect to variable declaration. Also I did not know that a variable can be assigned a value within the condition of the if statement, but knowing know that it can, and that variable assignment occurs before evaluation of the expression has lead me to what I think the answer is.

I feel know that this statement is true because the we know that $var now has a value of donut and when it is evaluated it is not empty, has a value of 0, or an empty string, therefore it should return true.

Is this correct?

Thank you for you help,

Alex

#4
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
  • Location:New York, NY

alexbeau said:

I feel know that this statement is true because the we know that $var now has a value of donut and when it is evaluated it is not empty, has a value of 0, or an empty string, therefore it should return true.

Correct.

#5
alexbeau

alexbeau

    Newbie

  • Members
  • Pip
  • 3 posts
Great,

Thank you two for your help.

Really cleared things up for me.

Alex




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users