Home > Software engineering >  Get the previous and next non empty elements in an associative array
Get the previous and next non empty elements in an associative array

Time:10-13

I have an associative array like the following:

$a = array("1" => "a", "2" => "", "3" => "", "4" => "f", "5" => "d", "6" => "c")

and I would like to have an array which consists of the previous and next elements of each index, but only the non empty one, like this

array containing the previous non empty element for each element of the original array:

$p = array("1" => "", "2" => "a", "3" => "a", "4" => "a", "5" => "f", "6" => "d")

array containing the next non empty element for each element of the original array:

$n = array("1" => "f", "2" => "f", "3" => "f", "4" => "d", "5" => "c", "6" => "")

if there is no previous element in the original array (first element) then that index in the next array is empty. correspondingly for the previous

What would be the fastest way to achieve this? Looping all the array for each element is doable but seems too slow to me. Is there any other way?

CodePudding user response:

You can achieve this all in one foreach loop for the "previous" case, because you only ever need to track the "last good value":

$p = [];
$lastNonEmpty = '';
foreach ( $a as $key => $value ) {
    $p[$key] = $lastNonEmpty;
    if ( ! empty($value) ) {
        $lastNonEmpty = $value;
    }
}

The "next" case is slightly trickier, because you need to iterate the array backwards. Depending on the size of your array, you could just reverse the array, apply the above, and then reverse back:

$n = [];
$lastNonEmpty = '';
foreach ( array_reverse($a, true) as $key => $value ) {
    $n[$key] = $lastNonEmpty;
    if ( ! empty($value) ) {
        $lastNonEmpty = $value;
    }
}

$n = array_reverse($n, true);

For a longer array, or one with large data in the values, it might be more efficient to get a reversed list of keys and then iterate over that picking the appropriate values, i.e.

foreach ( array_reverse(array_keys($a)) as $key ) {
    $value = $a[$key];
    // ...
  •  Tags:  
  • php
  • Related