PHP 的合并函数?

发布于 2024-07-24 19:41:34 字数 252 浏览 5 评论 0 原文

许多编程语言都有合并函数(返回第一个非 NULL 值,示例)。 遗憾的是,2009 年 PHP 还没有做到这一点。

在 PHP 本身获得合并函数之前,在 PHP 中实现一个合并函数的好方法是什么?

Many programming languages have a coalesce function (returns the first non-NULL value, example). PHP, sadly in 2009, does not.

What would be a good way to implement one in PHP until PHP itself gets a coalesce function?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

在巴黎塔顶看东京樱花 2024-07-31 19:41:35

我真的很喜欢 ?: 运算符。 不幸的是,它还没有在我的生产环境中实现。 所以我使用与此等效的方法:

function coalesce() {
  return array_shift(array_filter(func_get_args()));
}

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()));
}
顾挽 2024-07-31 19:41:35

值得注意的是,由于 PHP 对未初始化变量和数组索引的处理,任何类型的合并函数的用途都是有限的。 我很想能够做到这一点:

$id = coalesce($_GET['id'], $_SESSION['id'], null);

但是,在大多数情况下,这会导致 PHP 出现 E_NOTICE 错误。 在使用变量之前测试变量是否存在的唯一安全方法是直接在empty() 或isset() 中使用它。 如果您知道合并中的所有选项都已初始化,则 Kevin 建议的三元运算符是最佳选择。

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:

$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.

玩套路吗 2024-07-31 19:41:35

确保您准确地确定了您希望此函数如何与某些类型一起使用。 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>';
}

正如您所看到的,empty() 对于所有这些都返回 true,但 is_null() 只对其中的 2 个返回 true。

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()

$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.

柠檬色的秋千 2024-07-31 19:41:35

我正在扩展 Ethan Kent 发布的答案。 该答案将丢弃由于 的内部工作原理而评估为 false 的非空参数array_filter,这不是 coalesce 函数通常所做的事情。 例如:

echo 42 === coalesce(null, 0, 42) ? 'Oops' : 'Hooray';

哎呀

为了克服这个问题,需要第二个参数和函数定义。 callable 函数负责告诉 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'));
}

如果您可以简单地传递 isset< ,那就太好了/code> 或 'isset' 作为 array_filter 的第二个参数,但没有这样的运气。

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 coalesce function typically does. For example:

echo 42 === coalesce(null, 0, 42) ? 'Oops' : 'Hooray';

Oops

To overcome this, a second argument and function definition are required. The callable function is responsible for telling array_filter whether or not to add the current array value to the result array:

// "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 isset or 'isset' as the 2nd argument to array_filter, but no such luck.

情愿 2024-07-31 19:41:35

我目前正在使用这个,但我想知道它是否不能通过 PHP 5 中的一些新功能来改进。

function coalesce() {
  $args = func_get_args();
  foreach ($args as $arg) {
    if (!empty($arg)) {
    return $arg;
    }
  }
  return $args[0];
}

I'm currently using this, but I wonder if it couldn't be improved with some of the new features in PHP 5.

function coalesce() {
  $args = func_get_args();
  foreach ($args as $arg) {
    if (!empty($arg)) {
    return $arg;
    }
  }
  return $args[0];
}
霊感 2024-07-31 19:41:35

PHP 5.3+,带有闭包:

function coalesce()
{
    return array_shift(array_filter(func_get_args(), function ($value) {
        return !is_null($value);
    }));
}

演示:https://eval.in/187365

PHP 5.3+, with closures:

function coalesce()
{
    return array_shift(array_filter(func_get_args(), function ($value) {
        return !is_null($value);
    }));
}

Demo: https://eval.in/187365

永言不败 2024-07-31 19:41:35

返回第一个非 NULL 值的函数:

  function coalesce(&...$args) { // ... as of PHP 5.6
    foreach ($args as $arg) {
      if (isset($arg)) return $arg;
    }
  }

相当于 $var1 ?? $var2 ?? PHP 7+ 中为 null。

返回第一个非空值的函数:

  function coalesce(&...$args) {
    foreach ($args as $arg) {
      if (!empty($arg)) return $arg;
    }
  }

相当于 (isset($var1) ? $var1 : null) ?: (isset($var2) ? $var2 : null) ?: null PHP 5.3+。

上面将把数字字符串“0.00”视为非空。 通常来自 HTTP GET、HTTP POST、浏览器 cookie 或 MySQL 驱动程序,将浮点或小数作为数字字符串传递。

返回第一个未定义变量的函数,null、(bool)false、(int)0、(float)0.00、(string)""、(string)"0"、(string)"0.00"、( array)[]:

  function coalesce(&...$args) {
    foreach ($args as $arg) {
      if (!empty($arg) && (!is_numeric($arg) || (float)$arg!= 0)) return $arg;
    }
  }

用法如下:

$myvar = coalesce($var1, $var2, $var3, ...);

A function to return the first non-NULL value:

  function coalesce(&...$args) { // ... as of PHP 5.6
    foreach ($args as $arg) {
      if (isset($arg)) return $arg;
    }
  }

Equivalent to $var1 ?? $var2 ?? null in PHP 7+.

A function to return the first non-empty value:

  function coalesce(&...$args) {
    foreach ($args as $arg) {
      if (!empty($arg)) return $arg;
    }
  }

Equivalent to (isset($var1) ? $var1 : null) ?: (isset($var2) ? $var2 : null) ?: null in PHP 5.3+.

The above will consider a numerical string of "0.00" as non-empty. Typically coming from a HTTP GET, HTTP POST, browser cookie or the MySQL driver passing a float or decimal as numerical string.

A function to return the first variable that is not undefined, null, (bool)false, (int)0, (float)0.00, (string)"", (string)"0", (string)"0.00", (array)[]:

  function coalesce(&...$args) {
    foreach ($args as $arg) {
      if (!empty($arg) && (!is_numeric($arg) || (float)$arg!= 0)) return $arg;
    }
  }

To be used like:

$myvar = coalesce($var1, $var2, $var3, ...);
歌入人心 2024-07-31 19:41:34

php 5.3 中有一个新的运算符可以执行此操作:?:

// A
echo 'A' ?: 'B';

// B
echo '' ?: 'B';

// B
echo false ?: 'B';

// B
echo null ?: 'B';

来源:http://www.php.net/ChangeLog-5.php#5.3.0

There is a new operator in php 5.3 which does this: ?:

// A
echo 'A' ?: 'B';

// B
echo '' ?: 'B';

// B
echo false ?: 'B';

// B
echo null ?: 'B';

Source: http://www.php.net/ChangeLog-5.php#5.3.0

审判长 2024-07-31 19:41:34

PHP 7 引入了真正的 合并运算符

echo $_GET['doesNotExist'] ?? 'fallback'; // prints 'fallback'

如果??之前的值不存在或者为null,则取??之后的值。

相对于上述 ?: 运算符的改进是,?? 还可以处理未定义的变量,而不会抛出 E_NOTICE

PHP 7 introduced a real coalesce operator:

echo $_GET['doesNotExist'] ?? 'fallback'; // prints 'fallback'

If the value before the ?? does not exists or is null the value after the ?? is taken.

The improvement over the mentioned ?: operator is, that the ?? also handles undefined variables without throwing an E_NOTICE.

听风念你 2024-07-31 19:41:34

谷歌上首次点击“php合并”。

function coalesce() {
  $args = func_get_args();
  foreach ($args as $arg) {
    if (!empty($arg)) {
      return $arg;
    }
  }
  return NULL;
}

http://drupial.com/content/php-coalesce

First hit for "php coalesce" on google.

function coalesce() {
  $args = func_get_args();
  foreach ($args as $arg) {
    if (!empty($arg)) {
      return $arg;
    }
  }
  return NULL;
}

http://drupial.com/content/php-coalesce

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文