PHP: align two arrays by inserting empty spaces

Let’s say you have an array $a, representing the current state, and an array $b representing the new state. In order to visualise the difference (or diff for you GIT nerds), we would like to expand both arrays with empty elements so the matching elements align with each other ($a1 and $a2).

Note: We assume that both arrays are sorted by the same criteria. (In this case alphabetically.)

$a = [ 'A', 'F', 'F', 'G', 'H', 'Q', 'W', 'X', 'Z' ];
$b = [ 'D', 'F', 'H', 'H', 'R', 'S', 'X' ];


// merge both arrays
$merged = array_merge($a,$b);

// sort the merged array alphabetically
sort($merged);

$temp_a = $a;
$temp_b = $b;

$a1 = [];
$b1 = [];

foreach ($merged as $el) {

    // decide wether to add the element or an empty string in $a1
    $in_a = in_array($el, $temp_a);
    if ( $in_a ) {
        $a1[] = $el;
        unset($temp_a[array_search($el, $temp_a)]);
    } else {
        $a1[] = ' ';
    }

    // decide wether to add the element or an empty string in $b1
    $in_b = in_array($el, $temp_b);
    if ( $in_b ) {
        $b1[] = $el;
        unset($temp_b[array_search($el, $temp_b)]);
    } else {
        $b1[] = ' ';
    }

    // if the element was not present in any array, remove the last element from both arrays
    if (!$in_a && !$in_b) {
        array_pop($a1);
        array_pop($b1);
    }
}

print_r($a1);
print_r($b1);

// Result:
// $a1 = [ 'A', ' ', 'F', 'F', 'G', 'H', ' ', 'Q', ' ', ' ', 'W', 'X', 'Z' ];
// $b1 = [ ' ', 'D', 'F', ' ', ' ', 'H', 'H', ' ', 'R', 'S', ' ', 'X', ' ' ];