note 63920 deleted from language.operators.logical by nlopess
| From: | nlopess@php.net | Date: | Fri, 02 Jun 2006 08:55:52 +0000 |
| Subject: | note 63920 deleted from language.operators.logical by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-112913@lists.php.net to get a copy of this message | ||
Note Submitter: jhibbard at gmail dot com
----
I have read a few of these responses and quite honestly didn't find one that explained the
differences between the "||" and "OR" operators.
The best way to explain it is with an example.
<?php
echo "TEST 1:";
$choice1 = false;
$choice2 = "dog";
$default = "other";
$val = ($choice1 != false ? 'hah' : 'boo') || ($choice2 != false ?
'hah2' : 'boo2') || ($default != false ? 'hah3' : 'boo3');
echo $val;
echo "<BR /><BR /><BR />TEST 2:";
$choice1 = false;
$choice2 = "dog";
$default = "other";
//$val = $choice1 or $choice2 or $default;
$val = ($choice1 != false ? 'hah' : 'boo1' or ($choice2 != false ?
'hah2' : 'boo2') or ($default != false ? 'hah3' : 'boo3');
//$val = $choice1 or $choice2 or $default;
echo $val;
?>
If you use this code, you will have 2 responses. The first will be
TEST 1:1
and the second will be
TEST 2:boo1
The reason is because how the 2 operators respond. The "||" statement returns boolean
(true or false), thus the return value of 1.
The "OR" statement on the other hand, returns the actual statement on TRUE, thus why we
are getting boo1.
Now, let's give one more example and be done with it.
If we use these statements :
<?php
//Statement ONE with ||
$sql = "SELECT * FROM table";
$rst = myqsl_query($sql) || die(MySQL_Error());
//Statement TWO with OR
$sql = "SELECT * FROM table";
$rst = myqsl_query($sql) OR die(MySQL_Error());
?>
You will notice what I mean. Statement one will return true (or simply 1). Statement 2 will return
the actual result of the query (usually Resource ID #5 or the actual mysql error).
I hope this makes it more clear to the newbie/apprentice who is looking for a deeper explanation of
these logical operators.