isset() evolved
php’s isset() language construct is more than handy. It’s one of the language’s sweetest little features. Without it the loosely-typed (aka dynamically-typed) language might not nearly have been so successful.
Firstly, isset() is a language construct and not a function as some might think. That makes execution significantly faster than if it were a built-in function. I think the benchmark difference is 5 billionths of a millisec (just kidding). But you get my point & all you code-optimization zealots already knew that.
isset() is most widely used in this form (right?):
$sClientId = isset($_GET['client_id']) ? $_GET['client_id'] : false;
FYI the ternary operator is another of my fave language constructs. Its kewl.
Air-knee-ways with isset you can also:
Check if more than one variable is set in a dependant chain
$bAllSet = isset($iInteger, $dDouble, $sString);
As you can expect isset() returns false if one of the variables aren’t set. Okay, you prolly knew that too. Sorry moving along.
How about using isset to check the length of a string?
qbook:~ quinton$ php -a
Interactive mode enabled
<?php
$s = 'test string';
var_dump(isset($s{1}));
bool(true)
var_dump(isset($s{19}));
bool(false)
So you can cleverly use isset() in place of strlen() to check for empty strings or strings longer than an expected length. For one its faster but what’s really useful is that it’ll work regardless of the string’s character encoding whereas strlen() isn’t multi-byte aware thus returning buggy results.
isset() could be cooler
I would like isset() to be extended (not replaced) to wrap the above ternary operator example in a single call coz even the ternary/conditional operator can become tedious! So syntax like this would become possible:
<?php
// if $sVarNotSet is not set then return $sDefaultValue
$sMyVar1 = isset($sVarNotSet) { return $sDefaultValue; }
// and in case you need to do alot more to return the default value
$sMyVar2 = isset($sVarNotSet2) {
echo "var not set!";
// do stuff like read from a db, right some xml or even rm -f -r / *
// do more stuff
return $sValue;
}
// and just maybe an even shorter syntax like this could be possible ??
$sMyVar2 = isset($sVarNotSet3) : $sDefault;
Okay so my boredom is showing. Ever since the php okes have introduced namespaces i can’t think of any other features on my php wishlist… oh wait… native unicode support *gah*
3 years ago