Skip Navigation

Using PHP OR for Params

2 Comments | Latest by: Phil | Add Your Comment! »»

I'm sure this is old news to everyone, but I just figured it out. In PHP, you can use the or keyword in other places besides before die(). I'm starting to use this in conjunction with the "at sign" operator to quickly "param" variables. I'm sure I'll come up with more interesting uses later...

Before:

if ( ! isSet($a) ) {
	$a = 1;
}

Using an Inline IF. It's shorter, but not there yet...

$a = ( isSet($a) ) ? $a : 1;

After:

$a = @$a or $a = 1;

It's the shortest of all! The @ is there to suppress PHP's error when $a is not set.

Note: you have to use "or", you can't say:

$a = @$a || $a = 1;

It doesn't work the same way.

This is especially critial for big nerds like me who tweak their local development environtment to crank out every single PHP error or warning. (What do you mean you don't code like this? You like PHP ignoring non-declared variables?! I don't! But then again I come from ColdFusion which bitches over every non-declared variable, hence the CFPARAM tag...)

You could even use this idea in a loop if you wanted to get away from for ($i=0, $i < something.... etc.

do {
	$a = @$a+=1 or $a = 1;
	echo "\$a:  $a\n";
} while ($a < 5);

Sadly, PHP is not like Ruby, and you can't say:

$a = @$a or 1;  # i'm sure in ruby it's simpler

But anyway... Maybe this could be used to shorten PHP Fusebox's handling of the set verb in parsed files...

May 18, 2006

«« Previous Entry  ·  Next Entry »»

Comments

Mike!! Mike!!
Jul 4, 2008

Exercising the grey matter there, were you Phil?

What about speed? Have you benchmarked the 'or' approach? If it's faster then it would have a better chance of getting into the core files besides just being shorter :)

Phil Phil
Jul 4, 2008

No, I haven't bench marked it. But I will... I'll let you know. Good point about that. I guess I made that comment because I'm still in the "shorter is better" frame of mind from the app_cacheddata filesize battles.

How to Put Your Face Next to Your Comment

Add Your Comment to:  Using PHP OR for Params


(Required not Shown)

(Optional, and Linked with 'Follow')



"My mother used to say that there are no strangers, only friends you haven't met yet. She's now in a maximum security twilight home in Australia." - Dame Edna Everage