Get value if set, or default

php.internals

Griggs Domler

23 years ago
It's rare to find functionality that cannot be effectively implemented in userland PHP code, but this appears to be one of them. The issue here is the capability to check if an array index (or variable) is set, if so, return its value, or return a passed in default value. This can be accomplished using if statements or the ternary operator, but they quickly become tiresome for so routine a task. Especially when dealing with nested associative arrays, for example: $myVar = (isset($_SESSION['application']['section']['page']['title']))?$_SESSION[ 'application']['section']['page']['title']:"Default Title"; Wouldn't this be better: $myVar = getd($_SESSION['application']['section']['page']['title'],"Default Title"); At first glance defining a function that will accomplish this appears easy: function getd($var,$default='') { if(isset($var)) return $var; else return $default; } $myVar = getd($arr['noindex']); But this is not notice level compliant, producing an error if the index doesn't already exist. Re-writing the function to pass by reference seems to fix this at first glance: function getd(&$var,$default='') { . . . } $myVar = getd($arr['noindex']); It no longer gives a notice. But the call mentioned above will now create the index mentioned, setting its value to null, which, while not necessarily wrong, still means that a foreach iteration or array_keys() call will show that the key now exists. (though isset() will not.) Since writing a userland function to accomplish this seems impossible while maintaining notice-level compliance, could this be accomplished at the language level? Perhaps by adding a statement similar to isset? It would seem a very helpful addition to PHP and would not need to affect other language constructs.

Robert Cummings

23 years ago
Why not augment the userland function to the following: function getd( &$sourceArray, $key, $default=null ) { if( isset( $sourceArray[$key] ) ) { return $sourceArray[$key]; } return $default; } Cheers, Rob. On Mon, 2003-08-18 at 17:03, Griggs Domler wrote:
> It's rare to find functionality that cannot be effectively implemented > in userland PHP code, but this appears to be one of them. > > The issue here is the capability to check if an array index (or > variable) is set, if so, return its value, or return a passed in default > value. This can be accomplished using if statements or the ternary > operator, but they quickly become tiresome for so routine a task. > Especially when dealing with nested associative arrays, for example: > > $myVar = > (isset($_SESSION['application']['section']['page']['title']))?$_SESSION[ > 'application']['section']['page']['title']:"Default Title"; > > Wouldn't this be better: > > $myVar = > getd($_SESSION['application']['section']['page']['title'],"Default > Title"); > > At first glance defining a function that will accomplish this appears > easy: > > function getd($var,$default='') > { > if(isset($var)) > return $var; > else > return $default; > } > > $myVar = getd($arr['noindex']); > > But this is not notice level compliant, producing an error if the index > doesn't already exist. > > Re-writing the function to pass by reference seems to fix this at first > glance: > > function getd(&$var,$default='') > { > . . . > } > > $myVar = getd($arr['noindex']); > > > It no longer gives a notice. But the call mentioned above will now > create the index mentioned, setting its value to null, which, while not > necessarily wrong, still means that a foreach iteration or array_keys() > call will show that the key now exists. (though isset() will not.) > > Since writing a userland function to accomplish this seems impossible > while maintaining notice-level compliance, could this be accomplished at > the language level? Perhaps by adding a statement similar to isset? It > would seem a very helpful addition to PHP and would not need to affect > other language constructs.
-- .---------------------------------------------. | Worlds of Carnage - http://www.wocmud.org | :---------------------------------------------: | Come visit a world of myth and legend where | | fantastical creatures come to life and the | | stuff of nightmares grasp for your soul. | `---------------------------------------------'

Guy N. Hurst

23 years ago
Hi, The function Robert proposes only works for going one key deep. That means one would have to specify getd($arr['sublevel'],$subkey), which would then create the key 'sublevel'. (That is assuming one has access to the parent keys) I have addressed this in the following function: function arr_getd(&$space,$path,$default=""){ if (is_array($space) ): if (array_key_exists($path,$space) ): return $space[$path]; endif; if($path{0}=="$"): $path=substr($path,1); endif; if(strpos($path,"]")>0): $tmp_pos = strpos($path,"["); if ($tmp_pos>0): // rep arr x[.] $path = '["'.substr($path,0,$tmp_pos).'"]'.substr($path,$tmp_pos); endif; return eval("return (isset(\$space$path))?\$space$path:\$default;"); endif; endif; return $default; } Now, I can pass in a string representation like this: $val = arr_getd($arr,"['sublevel']['$subkey']","default"); This allows me to control at what point the reference autovivifies the passed-in array space. Unfortunately, this approach requires the use of eval in order to access the isset() function. Coupled with the logic and string functions, it takes a significant performance hit. Since I use this inside loops, I would very much appreciate a language-level implementation similar to isset(), which doesn't require that a variable be passed in as a string representation. Is such a thing is acceptable to the majority? Guy N. Hurst Robert Cummings wrote:
> Why not augment the userland function to the following: > > function getd( &$sourceArray, $key, $default=null ) > { > if( isset( $sourceArray[$key] ) ) > { > return $sourceArray[$key]; > } > > return $default; > } > > Cheers, > Rob. > > > On Mon, 2003-08-18 at 17:03, Griggs Domler wrote: > >>It's rare to find functionality that cannot be effectively implemented >>in userland PHP code, but this appears to be one of them. >> >>The issue here is the capability to check if an array index (or >>variable) is set, if so, return its value, or return a passed in default >>value. This can be accomplished using if statements or the ternary >>operator, but they quickly become tiresome for so routine a task. >>Especially when dealing with nested associative arrays, for example: >> >>$myVar = >>(isset($_SESSION['application']['section']['page']['title']))?$_SESSION[ >>'application']['section']['page']['title']:"Default Title"; >> >>Wouldn't this be better: >> >>$myVar = >>getd($_SESSION['application']['section']['page']['title'],"Default >>Title"); >> >>At first glance defining a function that will accomplish this appears >>easy: >> >>function getd($var,$default='') >>{ >> if(isset($var)) >> return $var; >> else >> return $default; >>} >> >>$myVar = getd($arr['noindex']); >> >>But this is not notice level compliant, producing an error if the index >>doesn't already exist. >> >>Re-writing the function to pass by reference seems to fix this at first >>glance: >> >>function getd(&$var,$default='') >>{ >> . . . >>} >> >>$myVar = getd($arr['noindex']); >> >> >>It no longer gives a notice. But the call mentioned above will now >>create the index mentioned, setting its value to null, which, while not >>necessarily wrong, still means that a foreach iteration or array_keys() >>call will show that the key now exists. (though isset() will not.) >> >>Since writing a userland function to accomplish this seems impossible >>while maintaining notice-level compliance, could this be accomplished at >>the language level? Perhaps by adding a statement similar to isset? It >>would seem a very helpful addition to PHP and would not need to affect >>other language constructs. >
-- Guy Hurst Senior Developer Web Teks, Inc. http://www.webteks.com Phone: 757.578.4923 Toll free: 877.Web.Teks Fax: 757.578.4996

Derick Rethans

23 years ago
On Mon, 18 Aug 2003, Guy N. Hurst wrote:
> Hi, > > The function Robert proposes only works for going one key deep.
Can you please keep discussions to php-general@ please. Derick
-- "Interpreting what the GPL actually means is a job best left to those that read the future by examining animal entrails." ------------------------------------------------------------------------- Derick Rethans http://derickrethans.nl/ International PHP Magazine http://php-mag.net/ -------------------------------------------------------------------------

Griggs Domler

23 years ago
Actually Guy was merely showing that this is indeed an internals issue, since a practical (or efficient) way of accomplishing this cannot be currently implemented in userland. I agree that further PHP userland code discussion is not appropriate for this list, but suffice it to say that we have looked at just about every possible way to implement this, and have come to the conclusion that a language statement, such as isset(), would be the best option. Thanks. Cheers, Griggs -----Original Message----- From: Derick Rethans [mailto:derick@php.net] Sent: Monday, August 18, 2003 5:54 PM To: Guy N. Hurst Cc: Robert Cummings; internals@lists.php.net Subject: Re: [PHP-DEV] Get value if set, or default On Mon, 18 Aug 2003, Guy N. Hurst wrote:
> Hi, > > The function Robert proposes only works for going one key deep.
Can you please keep discussions to php-general@ please. Derick
-- "Interpreting what the GPL actually means is a job best left to those that read the future by examining animal entrails." ------------------------------------------------------------------------ - Derick Rethans http://derickrethans.nl/ International PHP Magazine http://php-mag.net/ ------------------------------------------------------------------------ - On Mon, 2003-08-18 at 17:03, Griggs Domler wrote: > It's rare to find functionality that cannot be effectively implemented > in userland PHP code, but this appears to be one of them. > > The issue here is the capability to check if an array index (or > variable) is set, if so, return its value, or return a passed in > default value. This can be accomplished using if statements or the > ternary operator, but they quickly become tiresome for so routine a > task. Especially when dealing with nested associative arrays, for > example: > > $myVar = > (isset($_SESSION['application']['section']['page']['title']))?$_SESSIO > N[ > 'application']['section']['page']['title']:"Default Title"; > > Wouldn't this be better: > > $myVar = > getd($_SESSION['application']['section']['page']['title'],"Default > Title"); > > At first glance defining a function that will accomplish this appears > easy: > > function getd($var,$default='') > { > if(isset($var)) > return $var; > else > return $default; > } > > $myVar = getd($arr['noindex']); > > But this is not notice level compliant, producing an error if the > index doesn't already exist. > > Re-writing the function to pass by reference seems to fix this at > first > glance: > > function getd(&$var,$default='') > { > . . . > } > > $myVar = getd($arr['noindex']); > > > It no longer gives a notice. But the call mentioned above will now > create the index mentioned, setting its value to null, which, while > not necessarily wrong, still means that a foreach iteration or > array_keys() call will show that the key now exists. (though isset() > will not.) > > Since writing a userland function to accomplish this seems impossible > while maintaining notice-level compliance, could this be accomplished > at the language level? Perhaps by adding a statement similar to isset? > It would seem a very helpful addition to PHP and would not need to > affect other language constructs. -- -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php

Derick Rethans

23 years ago
On Mon, 18 Aug 2003, Griggs Domler wrote:
> have come to the conclusion that a > language statement, such as isset(), would be the best option.
If you search the archives, you would have noticed that this was brought up before, and shot down. Derick
-- "Interpreting what the GPL actually means is a job best left to those that read the future by examining animal entrails." ------------------------------------------------------------------------- Derick Rethans http://derickrethans.nl/ International PHP Magazine http://php-mag.net/ -------------------------------------------------------------------------

Guy N. Hurst

23 years ago
Derick Rethans wrote:
> On Mon, 18 Aug 2003, Griggs Domler wrote: > > >>have come to the conclusion that a >>language statement, such as isset(), would be the best option. > > > If you search the archives, you would have noticed that this was brought > up before, and shot down. > > Derick >
Ok, I have spent hours searching the archives and bugs database, and have come up with the following threads. I added a summarizing comment below each one. Notice that the only one that matches the default value request is the last one, which represents an OPEN item in the bugs database. :-) (And I added a comment to that entry.) P.S. I think calling the new construct default() is better than getd(). ****** Ternary operator enhancement for fluent code http://marc.theaimsgroup.com/?t=96220168300004&r=1&w=2 Andi: "Personally I don't want to add too many "weird" constructs to PHP. I think they reduce readability and go against one of the strengths of PHP which is an easy language for anyone with a C/Perl/Java background. These constructs are really cryptic." NOTE: a new language construct such as default() is not cryptic. ****** wrong implementation of isset()? http://marc.theaimsgroup.com/?l=php-dev&m=98148190704386&w=2 Andi: "unset() removes it from the symbol table and $x = NULL; changes it to be a NULL value. As far as PHP scripts are concerned it's pretty much the same thing. There are certain situations where you can't really nuke the variable but you want to mark it as dead." NOTE: a new language construct such as default() would not require changing isset() ****** builtin functions / constructs http://marc.theaimsgroup.com/?l=php-dev&m=98536452122073&w=2 Zeev: "There aren't too many built-in constructs that behave exactly like functions, as a matter of fact, I don't think there are any. The ones that come close: isset() and empty() - their different semantics is that they won't display a warning when fed a non existent argument (regardless of error reporting)..." NOTE: a new language construct such as default() would use semantics like this ****** variable_exists() patch http://marc.theaimsgroup.com/?l=php-dev&m=106081362832056&w=2 Zeev: "Don't use nulls as values and you won't have to use hacks. null is not a value, was never meant to be a value, and won't be a value." NOTE: a new language construct such as default() would not use nulls as values ****** userland macros http://marc.theaimsgroup.com/?l=php-dev&m=106123302908576&w=2 Timm: "use cc -E to do your own macros" NOTE: a new language construct such as default() would not require separate preprocessing ****** PROPOSAL: default value handling http://marc.theaimsgroup.com/?l=php-dev&m=104226313312160&w=2 Andi: "boolean operators must return true or false" NOTE: a new language construct such as default() is not a boolean operator ****** Requesting a nicer way of setting undefined variables to a default value. http://bugs.php.net/bug.php?id=24949 [OPEN] NOTE: a new language construct such as default() would provide this requested feature In conclusion, I could not find anywhere that this requested feature was shot down. Since it cannot be implemented reliably or effectively in userland, users stand to benefit from having this simple and commonly used feature incorporated into a language-level construct. At the same time, it is clearly a feature request/enhancement. The default() construct seems even more useful than either empty() or isset(). In web forms, a text field left blank is automatically given the value of an empty string, but forms validators must treat that as being 'not set'. So isset() is not enough for that check, since it would count the empty string as being set, which it is from a variable point of view. And empty() treats "0" as not set, so that is not enough if you need to allow submitting a zero in a form. if (default($_POST['qty'],"")!="") { } // vs if (isset($_POST['qty']) && $_POST['qty']!="") { } // vs if (!empty($_POST['qty']) || (isset($_POST['qty']) && $_POST['qty']=="0")) { } So, did I miss something in the archives where this was requested and shot down? Either way, thanks for your time, and for helping to make PHP what it is today. Guy N. Hurst