Joakim
Joakim

Reputation: 195

Replace one string in an array but leave others untouched in php

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']

Upvotes: 1

Views: 53

Answers (4)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

With array_reduce:

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

Upvotes: 1

Ashu
Ashu

Reputation: 1320

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"]

Upvotes: 0

Dan F
Dan F

Reputation: 85

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

Upvotes: 0

arkascha
arkascha

Reputation: 42915

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
)

Upvotes: 2

Related Questions