PHP array_merge empty values always less prioritar
Asked Answered
C

2

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;
  }
}
Charlton answered 18/12, 2015 at 8:12 Comment(6)
your array $b has 2 key2 indexes?Radices
!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.Playwriting
@roullie, thanks, this was a typoCharlton
@deceze, wouldn't it provide a php warning if I do "empty($a[$key])" and that the key doesn't exist?Charlton
No it won't, that's the point of empty. The Definitive Guide To PHP's isset And emptyPlaywriting
@deceze, thanks for the info. I did not remember this point, +1 for your anserCharlton
C
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!"
}
Chin answered 18/12, 2015 at 8:16 Comment(2)
Note that array_filter($a) + $b will do just fine as well.Playwriting
@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 ;)Charlton
T
4

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

$merge = array_merge($b, array_filter($a));
Tiberias answered 18/12, 2015 at 8:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.