PHP true & 'true' difference - php

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;
}
}

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

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.

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.

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

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.

Related

PHP If statement responding with all code rather than printing answer

I'm fairly new to programming. I'm trying to write what should be a fairly basic if, elseif piece of code for my database, but when it compiles it just prints the code from the first if statement all the way to the end. I've been going over it for days and can't work out where I'm going wrong
<!DOCTYPE html>
<html>
<body>
<?php
$row = "A1 Header";
$compulsary = FALSE;
$mutable = TRUE;
$included = FALSE;
if ($compulsary == FALSE and $mutable == TRUE) {
echo "<textarea style=background-color:yellow; name=\"message\">Please Enter</textarea><br>";
}
elseif ($compulsary == FALSE and $mutable == FALSE){
echo "'"$row"'";
}
elseif ($compulsary == True and $mutable == True) {
echo "<textarea style=background-color:yellow; name=\"message\">Please Enter</textarea><br>";
}
else {
echo "'"$row"'";
}
?>
</body>
</html>
You can do like this:
<!DOCTYPE html>
<html>
<body>
<?php
$row = "A1 Header";
$compulsary = FALSE;
$mutable = TRUE;
$included = FALSE;
if ($compulsary == FALSE and $mutable == TRUE) {
echo "<textarea style='background-color:yellow;' name='\"message\"'>Please Enter</textarea><br>";
}
elseif ($compulsary == FALSE and $mutable == FALSE){
echo $row;
}
elseif ($compulsary == TRUE and $mutable == TRUE) {
echo "<textarea style='background-color:yellow;' name='\"message\"'>Please Enter</textarea><br>";
}
else {
echo $row;
}
?>
</body>
</html>
try this
<!DOCTYPE html>
<html>
<body>
<?php
$row = "A1 Header";
$compulsary = FALSE;
$mutable = TRUE;
$included = FALSE;
if ($compulsary == FALSE and $mutable == TRUE) {
echo "<textarea style=background-color:yellow; name=\"message\">Please Enter</textarea><br>";
} elseif ($compulsary == FALSE and $mutable == FALSE) {
echo "'".$row."'";
} elseif ($compulsary == True and $mutable == True) {
echo "<textarea style=background-color:yellow; name=\"message\">Please Enter</textarea><br>";
} else {
echo "'".$row."'";
}
?>
</body>
</html>
I think you have a syntax error. Try this:
echo "'\"$row\"'";

Turning a nested PHP if statement into a single if statement

I am trying to figure out how to turn this nested if statement into a single if statement and having trouble getting it to run.
This is the original nested if statement:
if (isset($_REQUEST['gender']))
{
$gender = $_REQUEST['gender'];
if ($gender == 'M')
{
echo '<p><b>Good day, Sir!</b></p>';
}
elseif ($gender == 'F')
{
echo '<p><b>Good day, Madam!</b></p>';
}
else
{ // Unacceptable value.
$gender = NULL;
echo '<p class="error">Gender should be either "M" or "F"!</p>';
}
}
else
{ // $_REQUEST['gender'] is not set.
$gender = NULL;
echo '<p class="error">You forgot to select your gender!</p>';
}
This is my attempt:
if (isset($_REQUEST['gender']) && $gender == 'M')
{
$gender = $_REQUEST['gender'];
echo '<p><b>Good day, Sir!</b></p>';
}
elseif (isset($_REQUEST['gender']) && $gender == 'F')
{
$gender = $_REQUEST['gender'];
echo '<p><b>Good day, Madam!</b></p>';
}
elseif (isset($_REQUEST['gender']) && $gender != 'M' || (isset($_REQUEST['gender']) && $gender != 'F')
{ // Unacceptable value.
$gender = $_REQUEST['gender'];
$gender = NULL;
echo '<p class="error">Gender should be either "M" or "F"!</p>';
}
else
{ // $_REQUEST['gender'] is not set.
$gender = NULL;
echo '<p class="error">You forgot to select your gender!</p>';
}
I am not sure if it's because the $gender = $_REQUEST['gender']; is not executing, but any help would be appreciated.
You're checking variable $gender before you assign value to it. Following will help,
$gender = isset($_REQUEST['gender']) ? $_REQUEST['gender'] : "";
if ($gender == 'M')
{
echo '<p><b>Good day, Sir!</b></p>';
}
else if($gender == 'F')
{
echo '<p><b>Good day, Madam!</b></p>';
}
else if (!empty($gender) && ($gender != 'M' || $gender != 'F'))
{ // Unacceptable value.
echo '<p class="error">Gender should be either "M" or "F"!</p>';
}
else
{
echo '<p class="error">You forgot to select your gender!</p>';
}
A switch statement might be cleaner here.
switch ($_REQUEST['gender']) {
case null:
echo '<p class="error">You forgot to select your gender!</p>';
break;
case 'M':
echo '<p><b>Good day, Sir!</b></p>';
break;
case 'F':
echo '<p><b>Good day, Madam!</b></p>';
break;
default:
echo '<p class="error">Gender should be either "M" or "F"!</p>';
}
Here's the untested way I'd do this. I'd also do client side(javascript) checks first. I'm also presuming your gender field is text if is select you could take out the strtolower and trim.
<?php
if (empty($_REQUEST['gender']) || (strtolower(trim($_REQUEST['gender'])) != 'm' && strtolower(trim($_REQUEST['gender'])) != 'f')) {
//this should probably be checked client side for better usability, but better to check server side that we trust the data
echo '<p class="error">Please enter a valid Gender</p>';
} else {
$gender = strtolower(trim($_REQUEST['gender']));
echo '<p><b>Good day, ';
if ($gender == 'm') {
echo 'Sir!</b></p>';
} else {
echo 'Madam!</b></p>';
}
}

Explode with operator

I have a working code to restrict & validate subdomain.
$exp = explode('.', 'blog.mydomain.my.');
print_r($exp);
if(count($exp) == 3 && $exp[1] == "mydomain" && $exp[2] == "my" || $exp[3] == "") {
echo "<br>";
echo 'subdomain valid';
} else{
echo "<br>";
echo 'not valid';
}
now it need to check if its only false and I'm not so sure about the $exp[3] != "" comparison. From example below the subdomain should be valid but it give me error.
echo "<br>";echo "<br>";
$exp2 = explode('.', 'blog.mydomain.my.');
print_r($exp2);
if(count($exp2) != 3 || $exp2[1] != "mydomain" || $exp2[2] != "my" || $exp[3] != "") {
echo "<br>";
echo 'not valid';
}
Accepted numbers of subdomain is hello.mydomain.my or hello.mydomain.my. (with trailing dot). While hello.world.mydomain.my is not accepted.
Thanks in advance
This should give you what you want.
if(count($exp2) < 3 || count($exp2) > 4 || $exp2[1] != "mydomain" || $exp2[2] != "my" || (count($exp2) != 4 && $exp[3] != "")) {
echo "<br>";
echo 'not valid';
}
I would go for a regex solution, possibly even encapsulate it in a function:
function isValidDomain($domain)
{
return preg_match('/^[\w]+\.(mydomain)\.(my)\.?$/', $domain) ? true : false;
}
var_dump(isValidDomain('www.google.com'));
var_dump(isValidDomain('test.invalid.domain'));
var_dump(isValidDomain('hello.mydomain.my'));
var_dump(isValidDomain('hello.mydomain.my.'));

PHP If else if not working correctly

When I click y link,it is going to x.Why is that ?
x
y
<?php
if(isset($_REQUEST['hello']) == 'x')
{
echo 'x';
}
else if(isset($_REQUEST['hello']) == 'y'){
echo 'y';
}
else
{
echo "else";
}
try
if(isset($_REQUEST['hello']) && ($_REQUEST['hello']) == 'x') )
The isset function returns either true or false and you are comparing that return value with strings 'x' and 'y'.
Since you are using == and not ===, true == 'x' will return ture.
To fix this first you need to check if the variable is set and only then compare it.
if(isset($_REQUEST['hello']) && ($_REQUEST['hello']) === 'x'))
isset returns true or false, in both of these examples hello is set to something, so isset would return true (which does not equate to either x or y)
Hopefully this helps.
<?php
if(isset($_REQUEST['hello']) && $_REQUEST['hello']== 'x')
{
echo 'x';
}
else if(isset($_REQUEST['hello']) && $_REQUEST['hello'] == 'y'){
echo 'y';
}
else
{
echo "else";
}
?>
isset will check whether the request is set or not returns 0 or 1
x
y
<?php
if($_REQUEST['hello'] == 'x')
{
echo 'x';
}
else if($_REQUEST['hello'] == 'y'){
echo 'y';
}
else
{
echo "else";
}
<?php $myvar = $_REQUEST['hello'];
if($myvar == 'x')
{
echo 'x';
}
else if($myvar == 'y')
{
echo 'y';
}
else
{
echo 'else';
}
?>
Try this one

PHP quiz script answer highlight

I have a PHP script and MSSQL tables, I got the answer key in a variable stored in $right_answer and user selected answers in $user_answer_select THe format is something like this
5+10?
A) 10
B) 15
C) 20
D) 25
E) 50
Answer key: B
what I want to do is put a check mark next to B if its correct and a X if it is wrong, how would I make the if else statements here?
This is the code I currently have
if(($user_answer_select == $right_answer) && $user_answer_select == 'a') $a_sel = "<img src=\"tick_icon.gif\">";
else if(($user_answer_select == $right_answer) && $user_answer_select == 'b') $b_sel = "<img src=\"tick_icon.gif\">";
else if(($user_answer_select == $right_answer) && $user_answer_select == 'c') $c_sel = "<img src=\"tick_icon.gif\">";
else if(($user_answer_select == $right_answer) && $user_answer_select == 'd') $d_sel = "<img src=\"tick_icon.gif\">";
else if(($user_answer_select == $right_answer) && $user_answer_select == 'e') $e_sel = "<img src=\"tick_icon.gif\">";
This is wrong because some of the questions that don't have answers for are highlighted as true. What's the way to do this?
$answers = array ( "A"=>10, "B"=>15, "C"=>20, "D"=>25, "E"=>50 );
$right_answer = "B";
$user_selected_answer = "A";
echo "5+10?<br/>";
foreach ($answers as $key => $value) {
echo $key.") ".$value;
if ($value === $user_selected_answer) {
if ($value === $right_answer){ echo "check!"; }
else { echo "X"; }
}
echo "<br/>";
}
echo "Answer key: $right_answer";
if ( $user_answer_select == $right_answer ) {
$correct = true;
} else {
$correct = false;
}
Then in the correct answer on the form:
<?php echo $correct == true ? 'x' : ''; ?>

Categories