php PHP的合并函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1013493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Coalesce function for PHP?
提问by mikl
Many programming languages have a coalesce function (returns the first non-NULL value, example). PHP, sadly in 2009, does not.
许多编程语言都有一个合并函数(返回第一个非 NULL 值,例如)。遗憾的是,2009 年的 PHP 没有。
What would be a good way to implement one in PHP until PHP itself gets a coalesce function?
在 PHP 本身获得合并函数之前,在 PHP 中实现一个的好方法是什么?
回答by Kevin
There is a new operator in php 5.3 which does this: ?:
php 5.3 中有一个新的运算符,它可以执行此操作: ?:
// A
echo 'A' ?: 'B';
// B
echo '' ?: 'B';
// B
echo false ?: 'B';
// B
echo null ?: 'B';
回答by flori
PHP 7 introduced a real coalesce operator:
PHP 7 引入了一个真正的合并运算符:
echo $_GET['doesNotExist'] ?? 'fallback'; // prints 'fallback'
If the value before the ??does not exists or is nullthe value after the ??is taken.
如果 之前的值??不存在或者是 之后null的值??。
The improvement over the mentioned ?:operator is, that the ??also handles undefined variables without throwing an E_NOTICE.
对上述?:运算符的改进在于,它??也可以处理未定义的变量而不会抛出E_NOTICE.
回答by Will Shaver
First hit for "php coalesce" on google.
第一次在 google 上搜索“php coalesce”。
function coalesce() {
$args = func_get_args();
foreach ($args as $arg) {
if (!empty($arg)) {
return $arg;
}
}
return NULL;
}
回答by Ethan Kent
I really like the ?: operator. Unfortunately, it is not yet implemented on my production environment. So I use the equivalent of this:
我真的很喜欢 ?: 运算符。不幸的是,它还没有在我的生产环境中实现。所以我使用相当于这个:
function coalesce() {
return array_shift(array_filter(func_get_args()));
}
回答by Andrew
It is worth noting that due to PHP's treatment of uninitalised variables and array indices, any kind of coalesce function is of limited use. I would love to be able to do this:
值得注意的是,由于 PHP 对未初始化变量和数组索引的处理,任何类型的合并函数的用途都是有限的。我希望能够做到这一点:
$id = coalesce($_GET['id'], $_SESSION['id'], null);
But this will, in most cases, cause PHP to error with an E_NOTICE. The only safe way to test the existence of a variable before using it is to use it directly in empty() or isset(). The ternary operator suggested by Kevin is the best option if you know that all the options in your coalesce are known to be initialised.
但是,在大多数情况下,这会导致 PHP 出现 E_NOTICE 错误。在使用变量之前测试变量是否存在的唯一安全方法是直接在 empty() 或 isset() 中使用它。如果您知道合并中的所有选项都已初始化,那么 Kevin 建议的三元运算符是最佳选择。
回答by Peter Bailey
Make sure you identify exactly how you want this function to work with certain types. PHP has a wide variety of type-checking or similar functions, so make sure you know how they work. This is an example comparison of is_null() and empty()
确保您准确确定您希望此函数如何处理某些类型。PHP 具有多种类型检查或类似功能,因此请确保您了解它们的工作原理。这是 is_null() 和 empty() 的示例比较
$testData = array(
'FALSE' => FALSE
,'0' => 0
,'"0"' => "0"
,'NULL' => NULL
,'array()'=> array()
,'new stdClass()' => new stdClass()
,'$undef' => $undef
);
foreach ( $testData as $key => $var )
{
echo "$key " . (( empty( $var ) ) ? 'is' : 'is not') . " empty<br>";
echo "$key " . (( is_null( $var ) ) ? 'is' : 'is not') . " null<br>";
echo '<hr>';
}
As you can see, empty() returns true for all of these, but is_null() only does so for 2 of them.
如您所见,empty() 对所有这些都返回 true,但 is_null() 仅对其中 2 个这样做。
回答by Madbreaks
I'm expanding on the answer posted by Ethan Kent. That answer will discard non-null arguments that evaluate to false due to the inner workings of array_filter, which isn't what a coalescefunction typically does. For example:
我正在扩展Ethan Kent发布的答案。由于array_filter的内部工作原理,该答案将丢弃评估为 false 的非空参数,这不是coalesce函数通常所做的。例如:
echo 42 === coalesce(null, 0, 42) ? 'Oops' : 'Hooray';
Oops
哎呀
To overcome this, a second argument and function definition are required. The callablefunction is responsible for telling array_filterwhether or not to add the current array value to the result array:
为了克服这个问题,需要第二个参数和函数定义。的可调用的功能是负责告诉array_filter是否到当前数组值添加到结果数组:
// "callable"
function not_null($i){
return !is_null($i); // strictly non-null, 'isset' possibly not as much
}
function coalesce(){
// pass callable to array_filter
return array_shift(array_filter(func_get_args(), 'not_null'));
}
It would be nice if you could simply pass issetor 'isset'as the 2nd argument to array_filter, but no such luck.
如果您可以简单地将isset或'isset'作为第二个参数传递给array_filter,那就太好了,但没有这样的运气。
回答by Paulo Freitas
PHP 5.3+, with closures:
PHP 5.3+,带闭包:
function coalesce()
{
return array_shift(array_filter(func_get_args(), function ($value) {
return !is_null($value);
}));
}
Demo: https://eval.in/187365
回答by mikl
I'm currently using this, but I wonder if it couldn't be improved with some of the new features in PHP 5.
我目前正在使用它,但我想知道 PHP 5 中的某些新功能是否无法改进它。
function coalesce() {
$args = func_get_args();
foreach ($args as $arg) {
if (!empty($arg)) {
return $arg;
}
}
return $args[0];
}

