-1

I have two arrays like this.

Array1 ( [0] => 2014-04-24 [1] => null [2] => null [3] => 2014-04-26 [4] => null)

Array2 ( [0] => null [1] => 2014-04-02 [2] => 2014-04-01 [3] => null [4] => 2014-04-21)

As you can see in these two examples, where one is vacant, the position is filled in the other array. I would like to merge these to create one complete filled array.

Hinek
  • 9,519
  • 12
  • 52
  • 74
  • 4
    Have you any sample code that you've attempted? – Pebbl Apr 09 '14 at 13:13
  • No it's not a duplicate. I don't want to add another array onto the end of another, I want to merge both arrays so that the filled replaces the empty. It's quite simple if you bother to read it properly. – user3515417 Apr 09 '14 at 13:17
  • I agree, the solution to the linked 'duplicate' item would not work here. – Pebbl Apr 09 '14 at 13:18
  • This is the sample code. I have attempted.$dateprompt = (array_merge((array)$startdate, (array)$startts)); $dateprompt = (array_filter($dateprompt)); $dateprompt = (array_values($dateprompt)); – user3515417 Apr 09 '14 at 13:18
  • Sorry, I only see a dump of two arrays, no code? Unfortunately others have already posted answers that will work, without insisting on seeing your own workings first. The solution is quite achievable with a simple `foreach` and `if` statement, which is why it feels very much like a homework question. If it is, be sure to go and read up on [foreach](http://uk.php.net/manual/en/control-structures.foreach.php), [for](http://uk.php.net/manual/en/control-structures.for.php) and [array_map](http://uk.php.net/array_map) in hsz's case. – Pebbl Apr 09 '14 at 13:31
  • Yeah I have used foreach later in this formula but I could not figure out the correct syntax to give me the result I required. I thought that this would be the most simplistic way to put forward my problem. It is not a homework question, I just did not want to over-complicate this. – user3515417 Apr 09 '14 at 13:36

2 Answers2

1

Just try with:

$array1 = ['2014-04-24', null, null, '2014-04-26', null];
$array2 = [null, '2014-04-02', '2014-04-01', null, '2014-04-21'];

$output = array_map(function($value1, $value2){
    return $value1 ? $value1 : $value2;
}, $array1, $array2);

Output:

array (size=5)
  0 => string '2014-04-24' (length=10)
  1 => string '2014-04-02' (length=10)
  2 => string '2014-04-01' (length=10)
  3 => string '2014-04-26' (length=10)
  4 => string '2014-04-21' (length=10)
hsz
  • 148,279
  • 62
  • 259
  • 315
0
for ($i = 0; $i < count($arr1); $i++) {
   if($arr1[$i] == null) {
    $arr1[$i] = $arr2[$i];
   }
}

Would be the simplest way.

Omegavirus
  • 277
  • 4
  • 16