0

i have two variable , i want remove one variable from another variable

like :

$var1 = '4';
$var2 = '5,7,4,9';

if ($var1 Inside $var2)
{
// remove 4
}

//output

$var2 = '5,7,9';

Thank you ...

o6 qr
  • 95
  • 2
  • 7

2 Answers2

5

Since it is a string, I think the easiest is to first convert it to an array, remove the value, and put it back together again:

$values = explode(',', $var2);

if (($key = array_search($var1, $values)) !== false) {
    unset($values[$key]);
}

$var2 = implode(',', $values);

The part about deleting from the array is gratefully copied from this answer.

Community
  • 1
  • 1
GolezTrol
  • 114,394
  • 18
  • 182
  • 210
1

You can use a simple str_replace which uses regex:

<?php
    $var2 = str_replace("%$var1%", "", $var2); //remove the element if it is inside
    $var2 = str_replace("%,,%", ",", $var2); //Remove the ',' if it's needed
?>
Gwenc37
  • 2,064
  • 7
  • 18
  • 22