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?

1
  • You could remove blank entries from each array before merging... array_walk with callback function that removes the key if the value is blank, then merge. Commented Nov 12, 2013 at 21:39

2 Answers 2

2

One possible way to generate a 'union' of those arrays:

$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] => ''
*/

Demo.

The resulting array will be filled either with non-empty elements from the first array or (if check for non-emptiness fails) with any type of elements from the second array - the latter will serve as a kind of fallback.

Sign up to request clarification or add additional context in comments.

Comments

0

I guess it won't get much shorter than this:

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

If you don't want to modify the original arrays, just do the loop twice and add to a third array both times.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.