1

I'm gonna need a little help from you guys to fix this little code. The idea is to remove any numbers that are inside $remove_str from $list_str. As you can see I've already tried to solve the problem by turning both strings into arrays and simply loop through the list array searching for values inside the remove array and remove it if there's a match. However, the results are anything but what I expected. I've been toying around with it for a while now, but my head is spinning to much to see the solution.

<?php

$remove_str = '5,6,8,56,195';
$list_str = '1,3,6,9,34,150,195,213';

$remove_arr = explode(',', $remove_str);
$list_arr = explode(',', $list_str);

foreach($list_arr as $value){
    $position = array_search($value, $remove_arr);

    if($position !== false){
        unset($list_arr[$position]);
    } else {
        continue;
    }
}

$result = implode(',', $list_arr);

echo $result;

?>

Result:

1,6,9,150,195,213

Expected result:

1,3,9,34,150,213

LF00
  • 27,015
  • 29
  • 156
  • 295
icecub
  • 8,615
  • 6
  • 41
  • 70

1 Answers1

6

You can use array_diff,

array_diff($list_arr, $remove_arr);
LF00
  • 27,015
  • 29
  • 156
  • 295
  • The idea seems simple enough. Trying to work it out in my code now. Will let you know :) – icecub May 10 '17 at 02:10
  • 1
    Wow, that actually works like a charm! Thanks a lot! Will mark as answered as soon as SO lets me, haha – icecub May 10 '17 at 02:13