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 ...

3
  • 2
    is $var2 a string or an array? Commented May 8, 2014 at 13:00
  • What have you tried? See about Stack Overflow. Commented May 8, 2014 at 13:00
  • Convert the string into an array then look if it's inside Commented May 8, 2014 at 13:00

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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
?>

1 Comment

thnx , maybe ur code is good but i found another Best solution

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.