定义默认数组值的最简单方法
有没有更干净的方法来检查数组值以防止 PHP 通知?目前我这样做:
$email = (isset($_POST['user_email'])) ? $_POST['user_email'] : '';
$first_name = (isset($_POST['user_first_name'])) ? $_POST['user_first_name'] : '';
$last_name = (isset($_POST['user_last_name'])) ? $_POST['user_last_namel'] : '';
$birthday = (isset($_POST['user_last_name'])) ? $_POST['user_last_namel'] : '';
有没有一种方法可以做类似 JavaScript 的事情,只需提供默认值,就像这样?
user.email = response.email || '';
我不想禁止通知,但这些丑陋的检查使我的代码变得混乱。我使用的是 PHP 5.2.6。
Is there a cleaner way to check for array values to prevent PHP notices? Currently I do this:
$email = (isset($_POST['user_email'])) ? $_POST['user_email'] : '';
$first_name = (isset($_POST['user_first_name'])) ? $_POST['user_first_name'] : '';
$last_name = (isset($_POST['user_last_name'])) ? $_POST['user_last_namel'] : '';
$birthday = (isset($_POST['user_last_name'])) ? $_POST['user_last_namel'] : '';
Is there a way to do something like JavaScript where you just provide a default, like this?
user.email = response.email || '';
I don't want to suppress notices, but these ugly checks clutter up my code. I'm on PHP 5.2.6.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以创建一个函数:
如果需要,将其放入函数中还可以让您更轻松地进行额外的清理,例如
trim()
。您还可以传递将返回的默认值:
You can create a function:
Putting it in a function also let's you do additional sanitizing more easily, e.g.,
trim()
, if desired.You can also pass a default value that will be returned:
如果您有一组属性,那么一个简洁的选项是
array_merge
。请注意,首先使用默认值:然后按原样访问它们:
本地化有限变量集的更紧凑方法是
extract()
与array_intersect_key()
结合使用。但仅限于该组合 - 以防止导入任意变量:If you have a set of attributes, then one concise option is
array_merge
. Note that the defaults go first:Then just access them as is:
An even more compact way to localize a limited set of variables is
extract()
in combination witharray_intersect_key()
. But only in that combination - to prevent importing arbitrary variables:我至少见过三种方法来做到这一点。
添加带有默认值的数组
,其中
$options
是一个关联数组,包含$_POST
所具有的所有内容,但添加了来自$defaults
的键和值(除非有是$defaults
中特定键的$_POST
中的值,则$defaults
中的该特定键/值对将被忽略,并且该值特定键$_POST
不会被替换)。与默认数组合并
如 @mario 所示(使用
array_merge()
):使用辅助函数...
...例如 Kohana 的
Arr::get()
helper:它有一些轻松的优点替换默认值(默认为
NULL
)。它可以这样使用:或:
I have seen at least three ways of doing this.
Adding array with defaults
where
$options
is an associative array having everything$_POST
had, but with added keys and values from$defaults
(unless there was a value in$_POST
for specific key in$defaults
, then this specific key/value pair from$defaults
is ignored and value for this specific key in$_POST
is not replaced).Merging with array of defaults
As shown by @mario (use
array_merge()
):Using helper functions...
...such as Kohana's
Arr::get()
helper:which has some advantage of easily replacing default value (which, by default is
NULL
). It can be used like that:or:
您可以使用 DefaultArray 来自
You can use DefaultArray from NSPL: