Tutorial :PHP true & 'true' difference



Question:

Quick question. Is there a difference between

$success = true;  

and

$success = 'true';  

I know they are not '==' to each other, but is there a difference in using them?

EDIT: I found that using '===' instead of '==' when seeing if $success is false solved my problem. My question now is that, should I just use strings in a case like below, and stick with '=='?

    $User->ProcessLogin();  $loginsuccess = $User->ProcessLogin();    if ($loginsuccess == true) {          echo "<big>Success<big><br />";          echo "<p>We are now redirecting you to the member area.</p>";          echo "<meta http-equiv='refresh' content='=2;MyAccountNEW.php' />";  }  elseif ($loginsuccess == false) {          echo "<span class='sorry'><b>Sorry, your account could not be found.</span></b><div id='shopperlogin'> <img class='shopperlogintext' src='images/shopperlogin.png'>       <br />        <form method='post' action='loginNEW.php' name='loginform' id='loginform'>      <fieldset>          <label for='username'>Username:</label><input type='text' name='username' id='username' /><br />          <label for='password'>Password:</label><input type='password' name='password' id='password' /><br />          <input type='submit' name='login' id='login' value='Login' />      </fieldset>      </form></div>";      }  

Here's part of the class..

    function ProcessLogin() {      if (!empty($_POST['username']) && !empty($_POST['password'])) {              $username = mysql_real_escape_string($_POST['username']);              $password = md5(mysql_real_escape_string($_POST['password']));              $checklogin = mysql_query("SELECT * FROM users WHERE Username = '".$username."' AND Password = '".$password."'");                    if(mysql_num_rows($checklogin) == 1)                  {                       $row = mysql_fetch_array($checklogin);                      $email = $row['EmailAddress'];                        $_SESSION['Username'] = $username;                      $_SESSION['EmailAddress'] = $email;                      $_SESSION['LoggedIn'] = 1;                      $this->loggedin = true;                      $success = true;                  }                  else {                      $success = false;                  }                  return $success;              }          }  


Solution:1

Any non-empty string evaluates to true and an empty string evaluates to false. The following script might shed some light for you:

<?php  if('true' == true) {    echo "'true' == true";  } else {    echo "'true' != true";  }    echo '<br />';    if('false' == true) {    echo "'false' == true";  } else {    echo "'false' != true";  }    echo '<br />';    if('foo' == true) {    echo "'foo' == true";  } else {    echo "'foo' != true";  }    echo '<br />';    if('false' == false) {    echo "'false' == false";  } else {    echo "'false' != false";  }    echo '<br />';    if('' == true) {    echo "'' == true";  } else {    echo "'' != true";  }    echo '<br />';    if('' == false) {    echo "'' == false";  } else {    echo "'' != false";  }    ?>  

Here is the output:

'true' == true  'false' == true  'foo' == true  'false' != false  '' != true  '' == false  

As requested, here are some more examples comparing == with === for various values.

<?php  echo "<b>'true' vs. true</b><br />";    if('true' == true) {    echo "'true' == true<br />";  } else {    echo "'true' != true<br />";  }    if('true' === true) {    echo "'true' === true<br />";  } else {    echo "'true' !== true<br />";  }    echo "<br /><b>'false' vs. true</b><br />";    if('false' == true) {    echo "'false' == true<br />";  } else {    echo "'false' != true<br />";  }    if('false' === true) {    echo "'false' === true<br />";  } else {    echo "'false' !== true<br />";  }    echo "<br /><b>1 vs. true</b><br />";    if(1 == true) {    echo "1 == true<br />";  } else {    echo "1 != true<br />";  }    if(1 === true) {    echo "1 === true<br />";  } else {    echo "1 !== true<br />";  }    echo "<br /><b>0 vs. false</b><br />";    if(0 == false) {    echo "0 == false<br />";  } else {    echo "0 != false<br />";  }    if(0 === false) {    echo "0 === false<br />";  } else {    echo "0 !== false<br />";  }    echo "<br /><b>1 vs. 'true'</b><br />";    if(1 == 'true') {    echo "1 == 'true'<br />";  } else {    echo "1 != 'true'<br />";  }    if(1 === 'true') {    echo "1 === 'true'<br />";  } else {    echo "1 !== 'true'<br />";  }    echo "<br /><b>empty string '' vs. false</b><br />";    if('' == false) {    echo "'' == false<br />";  } else {    echo "'' != false<br />";  }    if('' === true) {    echo "'' === false<br />";  } else {    echo "'' !== false<br />";  }    ?>  

Output:

'true' vs. true

'true' == true  'true' !== true  

'false' vs. true

'false' == true  'false' !== true  

1 vs. true

1 == true  1 !== true  

0 vs. false

0 == false  0 !== false  

1 vs. 'true'

1 != 'true'  1 !== 'true'  

empty string '' vs. false

'' == false  '' !== false  


Solution:2

First is a boolean. 2nd is a string

You can see their difference with this.

$success = 'true';  $success2 = true;    var_dump($success);  var_dump($success2);  

And also check out the result from this

var_dump($success == $success2);  var_dump($success === $success2);  

You should also study this type comparison table. Real neat information and helps you understand PHP a bit more.


Solution:3

I always try to use the more restrictive === or !== when I absolutely positively need a boolean answer, so:

$success = 'true';  if( $success === 'false'){  ...  }  

Just in case.


Solution:4

true is a boolean, 'true' is a string.


Solution:5

Yes, there is a difference. Every value in a PHP variable (or almost any programming language) has a "type". When creating/assigning a value with quotes,

$foo = 'true';  

you are creating a value whose type is a string, and when creating/assigning a value without quotes, you are creating a variable whose type is boolean

$bar = true;  

Like some other modern, dynamic languages, PHP tries really hard to arrange things in such a way that you don't have to worry about things like type. For example, a lot of languages will NOT let you compare the equality of two variables if they aren't of the same type, so something like

if('true' == True) ...   

isn't valid code in python (you'll get an exception). PHP, on the other hand, tries to be nice and (behind the scenes) says "well, if you use any string in an equality operation, we'll pretend the string is of type boolean and true, unless it's a zero-length string". That's why, 90% of the time, you can get away with doing either.

However, there are differences. To start with the pedantic, the computer that PHP is running on needs to set aside more memory for a string than it does for a boolean. In this day and age it's a trivial amount, but waste not/want not.

More importantly though, there are times where PHP's type coercion does weird things that make no sense. For example, consider the following

if ("false" == false) {       echo "true\n";  } else {      echo "false\n";  }  

This statement will echo "false", even though intuitively you'd thing it would echo true, since "true" == true evaluates as true. There are a lot of edge cases like this where PHP will act in seemingly weird ways. So, in trying to make the general case simpler (let's convert variables for people), they made some less common cases more complex, which can lead to hard to track down bugs. Things get really gnarly when some people on your team understand the behind the scenes coercion, and others don't.

So, by and large, it's always best to return explicit booleans (no quotes) from methods and functions that are returning success. Experienced programmers expect it and inexperienced programmers will be baffled by some of the bugs that pop-up when strings are used instead.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »