Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array_merge empty values always less prioritar

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;
  }
}
like image 612
Bast Avatar asked Dec 18 '15 08:12

Bast


People also ask

What is the difference between array_merge () and Array_merge_recursive () in PHP?

The array_merge_recursive() function merges one or more arrays into one array. The difference between this function and the array_merge() function is when two or more array elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an array.

How does array merge work?

Description ¶ Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array. If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.


1 Answers

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!"
}
like image 76
Mihai Matei Avatar answered Nov 01 '22 15:11

Mihai Matei