0

I have these two arrays:

$array1 = array( '0' => 'apple', '1' => ''   , '2' => 'cucumber' );

$array2 = array( '0' => '',      '1' => 'bmw', '2' => 'chrysler' );

if I do this to merge these arrays:

$result_arr = array_merge($array1, $array2);
print_r( count ( array_filter($result_arr) ) );

the output would be 4.

However, I need to get the number 3. So, when there are two things on the same position (same key) count it only once.

Is it possible to merge/count elements in arrays like that?

4

2 回答 2

2

生成这些数组的“联合”的一种可能方法:

$first  = array( '0' => 'apple', '1' => ''   , '2' => 'cucumber', 3 => '');
$second = array( '0' => '',      '1' => 'bmw', '2' => 'chrysler', 3 => '');

$result = array_map(function($a, $b) {
  return $a ?: $b;
}, $first, $second);
print_r($result); 
/* 
[0] => 'apple'
[1] => 'bmw'
[2] => 'cucumber'
[3] => ''
*/

演示

结果数组将填充第一个数组中的非空元素或(如果检查非空性失败)第二个数组中的任何类型的元素 - 后者将用作一种后备。

于 2013-11-12T21:44:52.210 回答
0

我想它不会比这更短:

foreach ($array2 as $key->$value) {
    $array1[$key] = $value;
}

如果您不想修改原始数组,只需执行两次循环并两次添加到第三个数组。

于 2013-11-12T21:47:22.837 回答