Page 1 of 1

using && and/or || to replace if

Posted: Fri Jul 06, 2007 5:41 pm
by smudge
Hi all.
I was looking through some js code one day when I noticed that it did something like this:

Code: Select all

a=a||document
meaning,

Code: Select all

if(a){
  a=a;
}else{
  a=document;
}
I know it works because of short circuiting, but I was wondering if you could do this in php.
So,would something like this work?

Code: Select all

$var=$_POST['var1'] || 'default string';
or

Code: Select all

$var=isset($_POST['var1']) && $_POST['var1'];

Posted: Fri Jul 06, 2007 6:06 pm
by stereofrog
No, php uses "C semantic" for boolean operators, i.e. && and || only return true of false, as opposed to javascript and other languages that use "Perl semantic" where the first non-true / non-false value is returned. For example, "0 || 5" will return true (or 1) in php and c, and "5" in javascript.

Posted: Fri Jul 06, 2007 7:42 pm
by nathanr
you could always use ternary operators to do very similar..

Posted: Sun Jul 08, 2007 6:11 pm
by smudge
Ok. I didn't have enough time to test it myself because I had to leave, and just got back now.
Ternary operators are fine for some things, but I was just looking for a faster (run-time and typing time) solution. I mean, look at the difference:

Code: Select all

$var=isset($_POST['var1']) && $_POST['var1'];
$var=isset($_POST['var1']) ? $_POST['var1'] : false;
I don't know about you, but to me, the && looks cleaner. Oh well! Thanks for clearing that up.

Posted: Sun Jul 08, 2007 6:15 pm
by nathanr
I'm going to have a think about that one.. I'm sure there's something possible in that.

Posted: Sun Jul 08, 2007 6:21 pm
by volka
You might be interested in http://php6dev.blogspot.com/#ifsetor-as ... thing-else (php6 blog)