I have an array and variable. If the variable does not exist in the array it has to be added, otherwise it has t开发者_Go百科o 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
:
$valueExists = array_search($vr, $ar);
if ($valueExists !== false) {
unset($ar[$valueExists]);
} else {
$ar[] = $vr;
}
This will push the value to the end of the array if it doesn't exist and removes the value if it does.
First of all the call to
array_unique()
makes no sense, because if the value was in the array before, you want to delete it ..
you should break your foreach loop instead after you have found the key and set a boolean like keyFound = true.
After your loop, you can check if it has been set and if not, insert the variable to your array.
With your code, you are inserting your searchkey everytime a variable is compared and they are not the same.
Uhm... quite a mess you've got there.
You should use array_search
, as mensch said.
Here's your code a bit "remastered" to just work -- for learning purposes only.
<?php
function toggle($ar, $vr)
{
$found = false;
foreach ($ar as $i => $value)
{
if ($value == $vr)
{
unset ($ar[$i]);
$found = true;
}
}
if (!$found)
{
$ar[] = $vr;
$ar = array_unique($ar);
}
return $ar;
}
function printArray($ar)
{
foreach ($ar as $i => $value)
{
echo ($value . " - ");
}
echo ("<br/>");
}
$ar = array("a", "b", "c");
printArray($ar);
$ar = toggle($ar, "b");
printArray($ar);
$ar = toggle($ar, "k");
printArray($ar);
?>
You can do:
$ar = array("a","b","c");
$vr = "d";
if(($pos = array_search($vr,$ar)) !== false)
unset($ar[$pos]);
else
$ar[] = $vr;
first we use the array_search() to see if the value exists in the array. The return value of array_search() is false
if the value does not exist and it returns the corresponding key if the value exists. So we check the return value with false
. Also we collect the return value in a variable called $pos
. If the key exists, we delete the value from the array using the unset() method and if the value does not exist we add it.
精彩评论