2

So i'm working on a small php applications that combines four arrays. Now there is a possibility that some of the possible arrays will be null. I tried the following solution to merge the four arrays uniquely.

<?php
$a = [1,2,3,4,5];
$b = null;
$c = [5,4,3,2,1];
$d = [1,2];

$new_array;

if(is_array($a) && is_array($b) && is_array($c) && is_array($d))
{
    $new_array =  array_unique(array_merge($a,$b,$c,$d));
}else if(is_array($a) && is_array($b) && is_array($c))
{
        $new_array =  array_unique(array_merge($a,$b,$c));
}else if(is_array($a) && is_array($b))
{   
    $new_array =  array_unique(array_merge($a,$b));
}else{
    $new_array = $a;
}

print_r($new_array);
?>

I soon realized my code was highly dysfunctional in that it does not cater for all possible combinations of arrays while excluding the null variables.

How do I solve this. Ensuring that all the variables that are arrays are merged a nd those that are not are discarded. Thanks

John Kariuki
  • 4,966
  • 5
  • 21
  • 30

3 Answers3

5

how about this? putting all the array's in an array, so you can loop through them all easily, and use a custom in_array() function to check if they are already existing?

The good thing about this way is that it doesn't limit the script to just four array's, as it will loop through all the array's you get together.

$a = [1,2,3,4,5];
$b = null;
$c = [5,4,3,2,1];
$d = [1,2];

$array_stack = array($a, $b, $c, $d);

$new_array = array();

foreach($array_stack as $stack){
    if(!is_array($stack)) continue;
    foreach($stack as $value){
        if(!in_array($value, $new_array)) $new_array[] = $value;
    }
}

print_r($new_array);
aleation
  • 4,796
  • 1
  • 21
  • 35
3

maybe something like this :

<?php

$a = [1,2,3,4,5];
$b = null;
$c = [5,4,3,2,1];
$d = [1,2];

$new_array;

if(is_array($a)) $new_array = $a;
if(is_array($b)) $new_array =  array_unique(array_merge($new_array,$b));
if(is_array($c)) $new_array =  array_unique(array_merge($new_array,$c));
if(is_array($d)) $new_array =  array_unique(array_merge($new_array,$d));
?>
elune
  • 338
  • 1
  • 9
0

Old question, but going to give my input anyways. A more universal approach:

function multiple_array_merge() {
    $args = func_get_args();

    $array = [];
    foreach ($args as $i) {
        if (is_array($i)) $array = array_merge($array, $i);
    }

    return array_unique($array);
}

$a = [1, 2, 3, 4, 5];
$b = null;
$c = [5, 4, 3, 2, 1];
$d = [1, 2];

$merged = multiple_array_merge($a, $b, $c, $d);