Rach Mus
Rach Mus

Reputation: 37

PHP: Learning IF-ELSE-statement

What am I missing? Sorry for this very basic beginner's question.

Instructions:

On line 8, write an if / else statement, just like we did in the last exercise. Here's what the outline of the code looked like:

<?php
  if (this condition is true) {
    // do this code
  }
  else {
    // do this code instead
  }
?>

If your condition is true, your code should echo "The condition is true"

Otherwise (else) when it is false, your code should echo "The condition is false".

Make sure your condition evaluates to false, so that your program prints out "The condition is false".

This is what I wrote:

<head>
  </head>
  <body>
    <p>
      <?php
      $myName = "Suzie";
      $myAge = 35;
        // Write your if/elseif/else statement here!
        if($myName = "Rachelle")
        {
            echo "Hello Rachelle";
        }
        else {
            echo "what is your name";
        }

      ?>
    </p>
  </body>
</html>

Upvotes: 2

Views: 340

Answers (4)

Pranay Aher
Pranay Aher

Reputation: 434

You are assigining the value but not comparing (==).

Correct is:

 if($myName == "Rachelle") {
    echo "Hello Rachelle";
 } else {
    echo "what is your name";
 }

Upvotes: 2

Mad Angle
Mad Angle

Reputation: 2330

You should use double equal to parameter inside if condition to check the condition. Otherwise its considered as the assignment operation. Check the code below

<html>
  <head></head>
  <body>
    <p>
      <?php
        $myName = "Suzie";
        $myAge = 35;
        // Write your if/elseif/else statement here!
        if($myName == "Rachelle") {
          echo "Hello Rachelle";
        }
        else {
          echo "what is your name";
        }
      ?>
    </p>
  </body>
</html>

Upvotes: 0

Fadey
Fadey

Reputation: 430

So lets see why your condition if($myName = "Rachelle") returns true, the = operator is used to assign values to variables, now, PHP can cast an assignment operation to boolean, so it can "return" you a true value if the assignment has succeeded or false if it failed.

when you want to compare 2 values you should use the == operator:

(2 == "2") // returns true, compares the value

when you want to compare 2 values and thier types you should use the === operator:

(2 === "2") // returns false, compares values and type

Upvotes: 4

user4707168
user4707168

Reputation:

try this one!

 <head>
  </head>
  <body>
    <p>
      <?php
      $myName = "Suzie";
      $myAge = 35;
        // Write your if/elseif/else statement here!
        if($myName == "Rachelle")
        {
            echo "Hello Rachelle";
        }
        else {
            echo "what is your name";
        }

      ?>
    </p>
  </body>
</html>

Upvotes: 0

Related Questions