php - Deleting Elements In An Array Only When They Are Next To Each Other -
i have array composed of information looks following:
['jay', 'jay', 'jay', 'spiders', 'dogs', 'cats', 'john', 'john', 'john', 'dogs', 'cows', 'snakes']
what i'm trying remove duplicate entries if occur right next each other.
the correct result should following:
['jay', 'spiders', 'dogs', 'cats', 'john', 'dogs', 'cows', 'snakes']
i'm using php kind of logic able me out problem.
here code i've tried far:
$clean_pull = array(); $counter = 0; $prev_value = null; foreach($pull_list $value) { if ($counter == 0) { $prev_value = $value; $clean_pull[] = $value; } else { if ($value != $pre_value) { $pre_value = value; } } echo $value . '<br>'; }
francis, when run following code:
$lastval = end($pull_list); ($i=count($pull_list)-2; $i >= 0; $i--){ $thisval = $pull_list[$i]; if ($thisval===$lastval) { unset($pull_list[$i]); } $lastval = $thisval; } # optional: reindex array: array_splice($pull_list, 0, 0); var_export($pull_list);
, these results:
array ( 0 => 'nj lefler', 1 => 'deadpool', 2 => 'nj lefler', 3 => 'captain universe: hero you', 4 => 'nj lefler', 5 => 'the movement', 6 => 'nj lefler', 7 => 'the dream merchant', 8 => 'nolan lefler', 9 => 'deadpool', 10 => 'nolan lefler', 11 => 'captain universe: hero you', 12 => 'nolan lefler', 13 => 'the movement', 14 => 'tom smith', 15 => 'deadpool', 16 => 'tom smith', 17 => 'captain universe: hero you', )
your approach (a $prev_value
variable) should work fine , don't need counter.
your use of $counter
why code doesn't work--the first half of if
statement executed because $counter
never incremented; , second half compares values. thing need compare current value previous value , include current value if differs (or remove if it's same).
it's easier see algorithm if use functional reduction. here example using array_reduce
:
$a = array('jay', 'jay', 'jay', 'spiders', 'dogs', 'cats', 'john', 'john', 'john', 'dogs', 'cows', 'snakes'); $na = array_reduce($a, function($acc, $item){ if (end($acc)!==$item) { $acc[] = $item; } return $acc; }, array()); var_export($na);
note comparison of var_export($a)
(your original array) , var_export($na)
(the result produced code):
$a = array ( $na = array ( 0 => 'jay', 0 => 'jay', 1 => 'jay', 1 => 'spiders', 2 => 'jay', 2 => 'dogs', 3 => 'spiders', 3 => 'cats', 4 => 'dogs', 4 => 'john', 5 => 'cats', 5 => 'dogs', 6 => 'john', 6 => 'cows', 7 => 'john', 7 => 'snakes', 8 => 'john', ) 9 => 'dogs', 10 => 'cows', 11 => 'snakes', )
the array_reduce()
method same thing following code:
$na = array(); foreach ($a $item) { if (end($na)!==$item) { $na[] = $item; } }
instead of returning copy of array, can modify array in-place using same algorithm starting end of array:
$lastval = end($a); ($i=count($a)-2; $i >= 0; $i--){ $thisval = $a[$i]; if ($thisval===$lastval) { unset($a[$i]); } $lastval = $thisval; } # optional: reindex array: array_splice($a, 0, 0); var_export($a);
Comments
Post a Comment