如果不存在则将元素添加到数组中,如果存在则将其删除
<?php
$hackers = array ('Alan Kay', 'Peter Norvig', 'Linus Trovalds', 'Larry Page');
AddOrRemove('Sezar mbar',$hackers);
答案 0 :(得分:1)
喜欢
function AddOrRemove($val,&$hackers) {
$index = array_search($val,$hackers);
if($index === false) {
$hackers[] = $val;
} else {
unset($hackers[$index]);
}
}
答案 1 :(得分:0)
使用以下代码检查:
<?php
$hackers = array ('Alan Kay', 'Peter Norvig', 'Linus Trovalds', 'Larry Page');
if(in_array('Sezar mbar',$hackers)) // if value is in array
{
if(($key = array_search('Sezar mbar', $hackers)) !== false) { // find the key and delete the value
unset($hackers[$key]);
}
}
else // if value is not in array
{
array_push($hackers,'Sezar mbar'); // push value into the array
}
答案 2 :(得分:0)
试试这个
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Mac", $os)) {
$os = array_diff($os, array('Mac'));
}else
{
array_push($os,"Mac");
}
var_dump($os);
希望这会对你有帮助.....
答案 3 :(得分:0)
$hackers = array ('Alan Kay', 'Peter Norvig', 'Linus Trovalds', 'Larry Page');
function AddOrRemove($text, $array) {
$exists = false;
$index = 0;
for ($i=0; $i< count($array); $i++){
if ($array[$i] == $text){ $exists = true; $index = $i; break; }
}
if ($exists){
unset($array[$i]);
}
else {
array_push($array, $text);
}
echo count($array);
}
AddOrRemove('Sezar mbar',$hackers);