1

Say I have an array of strings like this:

$in_arr = ['a', 'a', 'b', 'b', 'a', 'b', 'b', 'a', 'a', 'b'];

I would like an efficient way to merge all a's into a single value but leave the b's untouched so the result will be:

['a', 'b', 'b', 'a', 'b', 'b', 'a', 'b']
3
  • you want to marge all 'a's or only continuous occurrence of 'a' Commented Jul 11, 2017 at 8:54
  • Looks like continuous occurrence... Commented Jul 11, 2017 at 8:54
  • Yes, so a sequence of a's becaomes just one single a but all b's should be left as they are Commented Jul 11, 2017 at 8:55

4 Answers 4

2

This is a possible solution:

<?php
define('ASPECT', 'a');
$input = ['a', 'a', 'b', 'b', 'a', 'b', 'b', 'a', 'a', 'b'];
$output = [];
array_walk($input, function($entry) use (&$output) {
    if (($entry != ASPECT) || (end($output) != ASPECT)) {
        $output[] = $entry;
    }
});
print_r($output);

The output obviously is:

Array
(
    [0] => a
    [1] => b
    [2] => b
    [3] => a
    [4] => b
    [5] => b
    [6] => a
    [7] => b
)
Sign up to request clarification or add additional context in comments.

Comments

1

With array_reduce:

$res = array_reduce($arr, function ($c, $i) {
    if ( $i!='a' || end($c)!='a' )
        $c[] = $i;
    return $c;
}, []);

Comments

0

You could iterate through the list and only add strings to a new list if they're not your key string or if they are different from the previous string, something like this:

$in_arr = ['a', 'a', 'b', 'b', 'a', 'b', 'b', 'a', 'a', 'b'];
$new_arr = [];

$last = '';
$key = 'a';

foreach ($in_arr as $item) { 
    if ($key == $item and $item == $last) {
        continue;
    }

    $last = $item;
    array_push($new_arr, $item);
}

echo "[";
foreach( $new_arr as $value ){
    echo $value.", ";
}
echo "]";

produces

[a, b, b, a, b, b, a, b, ]

Edit: PHP sandbox

Comments

0

You Require code :

<?php
$in_arr = array('a', 'a', 'b', 'b', 'a', 'b', 'b', 'a', 'a', 'b');

$last_temp = '';
for($i=0;$i<count($in_arr);$i++)
{
    if($last_temp == $in_arr[$i] && $in_arr[$i]=='a')
    {
        unset($in_arr[$i]);
        $in_arr = array_values($in_arr);
    }
    else
    {
        $last_temp = $in_arr[$i];
    }
}

echo json_encode($in_arr);

Output :

["a","b","b","a","b","b","a","b"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.