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;
  }
}
6
  • 1
    your array $b has 2 key2 indexes? Commented Dec 18, 2015 at 8: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. Commented Dec 18, 2015 at 8:20
  • @roullie, thanks, this was a typo Commented Dec 18, 2015 at 8:28
  • @deceze, wouldn't it provide a php warning if I do "empty($a[$key])" and that the key doesn't exist? Commented Dec 18, 2015 at 8:31
  • No it won't, that's the point of empty. The Definitive Guide To PHP's isset And empty Commented Dec 18, 2015 at 8:32

2 Answers 2

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!"
}
Sign up to request clarification or add additional context in comments.

2 Comments

Note that array_filter($a) + $b will do just fine as well.
@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 ;)
4

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

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

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.