6

My goal is to merge 2 different arrays.

I have table "a" & "b". Data from table "a" are more prioritar.

PROBLEM: if a key from "a" contains an empty value, I would like to take the one from table "b".

Here is my code:

<?php

$a = array('key1'=> "key1 from prioritar", 'my_problem'=> "");

$b = array('key1'=> "key1 from LESS prioritar", 'key2'=>"key2 from LESS prioritar", 'my_problem'=> "I REACHED MY GOAL!");

$merge = array_merge($b, $a);

var_dump($merge);

Is there a way to do this in one function without doing something like below?

foreach($b as $key => $value)
{
  if(!array_key_exists($key, $a) || empty($a[$key]) ) {
    $a[$key] = $value;
  }
}
Bast
  • 661
  • 2
  • 7
  • 23
  • 1
    your array `$b` has 2 `key2` indexes? – roullie Dec 18 '15 at 08:15
  • 1
    `!array_key_exists || empty` is nonsense. Using either one will do just fine, depending on whether you're interested in a comparison to `false` or not. Using both together is the same as just using `empty`. – deceze Dec 18 '15 at 08:20
  • @roullie, thanks, this was a typo – Bast Dec 18 '15 at 08:28
  • @deceze, wouldn't it provide a php warning if I do "empty($a[$key])" and that the key doesn't exist? – Bast Dec 18 '15 at 08:31
  • No it won't, that's the point of `empty`. [The Definitive Guide To PHP's isset And empty](http://kunststube.net/isset/) – deceze Dec 18 '15 at 08:32
  • @deceze, thanks for the info. I did not remember this point, +1 for your anser – Bast Dec 18 '15 at 08:40

2 Answers2

5

You can use array_replace and array_filter

$mergedArray = array_replace($b, array_filter($a));

The result would be:

array(3) {
  ["key1"]=>
  string(19) "key1 from prioritar"
  ["key2"]=>
  string(24) "key2 from LESS prioritar"
  ["my_problem"]=>
  string(18) "I REACHED MY GOAL!"
}
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
  • 2
    Note that `array_filter($a) + $b` will do just fine as well. – deceze Dec 18 '15 at 08:26
  • 1
    @Matei, thanks a lot. This is (almost) what I was searching for. "almost" because I initially wanted to keep the empty value from "$a" if the key doesn't exist in "$b". But this is already much better than a foreach ;) – Bast Dec 18 '15 at 08:38
4

Just array_filter() $a which will remove any item with '' value.

$merge = array_merge($b, array_filter($a));