using && and/or || to replace if

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
smudge
Forum Contributor
Posts: 151
Joined: Sun May 20, 2007 12:13 pm

using && and/or || to replace if

Post 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'];
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post 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.
User avatar
nathanr
Forum Contributor
Posts: 200
Joined: Wed Jun 07, 2006 5:46 pm

Post by nathanr »

you could always use ternary operators to do very similar..
smudge
Forum Contributor
Posts: 151
Joined: Sun May 20, 2007 12:13 pm

Post 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.
User avatar
nathanr
Forum Contributor
Posts: 200
Joined: Wed Jun 07, 2006 5:46 pm

Post by nathanr »

I'm going to have a think about that one.. I'm sure there's something possible in that.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

You might be interested in http://php6dev.blogspot.com/#ifsetor-as ... thing-else (php6 blog)
Post Reply