php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #24949 Requesting nicer way of setting undefined variables to default val. ifsetor / ?:
Submitted: 2003-08-05 05:28 UTC Modified: 2010-11-18 23:07 UTC
Votes:12
Avg. Score:4.6 ± 0.5
Reproduced:11 of 11 (100.0%)
Same Version:7 (63.6%)
Same OS:7 (63.6%)
From: nickj-php at nickj dot org Assigned: jani (profile)
Status: Closed Package: *General Issues
PHP Version: 6 OS: *
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
MUST BE VALID
Solve the problem:
1 + 25 = ?
Subscribe to this entry?

 
 [2003-08-05 05:28 UTC] nickj-php at nickj dot org
Description:
------------
Requesting a nicer way of setting undefined variables to a default value.

It gets a bit repetitive and ugly having to use statements like:

        $title   = isset($vals["title"])      ? $vals["title"]      : "";
        $first   = isset($vals["first_name"]) ? $vals["first_name"] : "";
        $surname = isset($vals["surname"])    ? $vals["surname"]    : "";

This seems to be a recurrent requirement, so ideally there would be some way of doing this, along the lines of :

function noUnset($val, $default="") {
    return isset($val) ? $val : $default;
}

Unfortunately a user function such as the above cannot be defined to do this, since the first argument passed to the function would be unset.

For example, this code will generate an error:

==========================================

error_reporting (E_ALL);

function noUnset($val, $default="") {
    return isset($val) ? $val : $default;
}

if (isset($x)) unset ($x);
// $x = 2; // works OK if this line is uncommented
print noUnset($x, "not set");
// Above line generates an error as noUnset cannot be called with $x, because it is not set - catch-22 !

==========================================

This code generates an "Undefined variable:  x" error.

Ideally there would be slightly nicer way of setting defaults than a bank is "isset" statements, that would work without generating an error, even with all error reporting options turned on.


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2003-08-18 21:27 UTC] hurst at webteks dot com
That there is no way to write a function to handle unset vars is also something I have come across. 

One solution would be to use the @-symbol:

print noUnset(@$x, "not set");

However, the @-symbol is not guaranteed to work, since
a user-defined error handler will ignore it.

Only isset(), unset(), and empty() can handle undefined variables without implicitly declaring them.


Perhaps a new construct can be made available to handle
this common case.


default($var['not_a_key'],"default_value") => "default_value"


It would work like the following function, but using the
caller environment (which could be from within another function):

function default($var,$default="")
{
    return isset($var)?$var:$default;
}

Using "" for the inherent default value makes sense
for web interfaces.
 [2003-08-22 12:00 UTC] xuefer at 21cn dot com
it would be nice to use "?:" operator as new c++ language

$a = isset($a) ? $a : "";
->
$a = $a ?: "";

$a = $a ?: $b ?: $c ?: $d;
better than:
$a = default($a, $b, $c, $d);
 [2003-10-09 18:45 UTC] marcus at deck16 dot com
I also came across that "problem" and voted for that "bug".

It is possible to write a function though. Just pass the var Name as a string:

<input type="text" name="Email" size="24" value="<?php echo Set_Form_Value('Email'); ?>">
 [2005-01-02 02:42 UTC] nickj-php at nickj dot org
From Derick Rethans PHP Look Back 2004 [http://www.derickrethans.nl/month-2004-12.php?item=20041231#20041231], there were two discussions during the year on this topic on the PHP-DEV mailing list, which I am adding links to here (as they help to summarize various aspects of this) :
1) April 2004: http://groups.google.com.au/groups?threadm=c5m94m$31kh$1@FreeBSD.csie.NCTU.edu.tw
2) July 2004: http://groups.google.com.au/groups?threadm=cci54b$t6s$1@FreeBSD.csie.NCTU.edu.tw
 [2006-01-19 19:03 UTC] chris dot vigelius at gmx dot net
Workaround: You can implement the functionality using references

error_reporting (E_ALL);

function _ifsetor(&$field, $defaultvalue) {
	return (isset($field))?$field:$defaultvalue;	
}

$v1 = $v2 = 'x';
echo _ifsetor($v1, 'v1 is not set');
unset($v2);
echo _ifsetor($v2, 'v2 is not set');

This works in 5.1.2 without warnings (haven't checked other versions, though)
 [2006-01-20 01:46 UTC] nickj-php at nickj dot org
That workaround works for most situations, but maybe not all, such as for constants (which cannot be passed-by-reference):

$val     = _ifsetor(null, 'some value');
$php_ver = _ifsetor(PHP_VERSION, 'some value');

However, I'm not sure whether such a thing should ideally work (i.e. perhaps it's best that this doesn't work, but on the other hand I can't see why it shouldn't) - so I'm honestly not sure.

The main point though is that it's a common requirement, especially for web forms, to have to test for a set value, and supply a default if none is set - so it could be good if the language core natively included this functionality.

Happily, it looks like this is going to happen in PHP6. Please see: http://www.php.net/~derick/meeting-notes.html#ifsetor-as-replacement-for-foo-isset-foo-foo-something-else  (long URL, so may have wraparound issues).

The outcome was that PHP will get a new "?:" construct, like the one mentioned previously by Xuefer. Personally, I realise now that this is a far neater approach that having a function (such as ifsetor/noUnset/default), so kudos to the PHP developers.
 [2010-11-18 23:07 UTC] jani@php.net
-Status: Open +Status: Closed -Package: Feature/Change Request +Package: *General Issues -Operating System: Any +Operating System: * -PHP Version: PHP6 +PHP Version: 6 -Assigned To: +Assigned To: jani
 [2010-11-18 23:08 UTC] jani@php.net
?: exists since 5.3.
 [2010-11-19 00:27 UTC] ken at smallboxcms dot com
I personally have never found a use for ?: and think at best it rarely would solve the problem that ifsetor has been requested for. because ?: throws a notice when the variable being tested for is undefined one is still forced to use the longer sintax

$foo = isset($_REQUEST['name_of_really_long_variable']) ? $_REQUEST['name_of_really_long_variable'] : null;

Hands down my biggest peeve with PHP

Also sadly there is no way to implement something in userland because testing for a new element in an array has the unfortunate side effect of also setting that element. Only solution is an operator that works like isset or empty but has the potential to return the value of the variable being tested for instead of true or false.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 19 00:01:29 2024 UTC