使用PHP合并数组

Coalesce isn't really the right word as it returns the first non-NULL value, but hopefully it conveys the intent.

Is there a more-readable and concise way to do get the first defined value of foo from $arr, $_GET, and then $_POST?

function foo($arr=array())
{
   $arr['bar']=isset($arr['bar'])?$arr['bar']:(isset($_GET['bar'])?$_GET['bar']:(isset($_POST['bar'])?$_POST['bar']:NULL));
   //  ....
}

array_merge is the function you're looking for. Precedence given to the last parametric array.

$allData = array_merge($_POST, $_GET, $arr);
return $allData['bar'];

There are a few answers here that could work, although none are great to look at: Using short circuiting to get first non-null variable

Chosen answer from above modified for your variables:

@$arr['bar'] = $arr['bar'] ?: $_GET['bar'] ?: $_POST['bar'] ?: NULL;

There are a couple issues with using array_merge or the + operator with arrays assuming there is a defined offset but the value happens to be null.

Here are three different approaches and the output from each.

<?php

$a = ['foo' => null];
$b = ['foo' => 'bar_b'];
$c = ['foo' => 'bar_c'];

var_dump($a + $b + $c);

var_dump(array_merge($c, $b, $a));  //reverse order here!

function getFirstSetOffsetFromArrays($key, $arr) {
  foreach($arr as $v) {
    if (isset($v[$key]) && !empty($v[$key])) {
      return $v[$key];
    }
  }
}

var_dump(getFirstSetOffsetFromArrays('foo', [$a, $b, $c]));

Output:

array(1) { ["foo"]=> NULL }
array(1) { ["foo"]=> NULL }
string(5) "bar_b" 

There are several good examples here already, but I'd prefer to:

$arr['bar'] = 
    current(filter_var_array($arr, ['bar' => FILTER_DEFAULT])) ?: 
    filter_input(INPUT_GET, 'bar', FILTER_DEFAULT) ?: 
    filter_input(INPUT_POST, 'bar', FILTER_DEFAULT) ?: 
    null;

Advantages

  • Key used only once per array (easier to maintain).
  • More readable.
  • Selects first valid input (eg first valid number or e-mail).
  • Does not trigger undefined index notice.
  • No need to use @.

Disadvantages

  • Actually longer than original code.
  • Makes sense only when $_GET and $_POST are used, otherwise too complicated.