I have an array and variable.
If the variable does not exist in the array it has to be added, otherwise it has to be removed.
Why the following code does not work?
$ar = ["a","b","c"];
$vr = "b";
foreach ($ar as $i => $value) {
if ($value == $vr) {
unset ($ar[$i]);
} else {
$ar[] = $vr;
$ar = array_unique($ar);
}
}
Thanks.
I assume you’re using PHP, if so the array declaration isn’t correct, it should be:
$ar = array("a", "b", "c");The code in your question is rather complex – and a bit of mess, I’m sorry to say – for what you want it to do. To achieve what you want, you could use
array_search:This will push the value to the end of the array if it doesn’t exist and removes the value if it does.