Am einfachsten wäre es wohl, eine Funktion mit einer foreach-Schleife zu verwenden:
//This functions deletes the elements of an array $original that are equivalent to the value $del_val
//The function works by reference, which means that the actual array used as parameter will be modified.
function delete_value(&$original, $del_val)
{
//make a copy of the original, to avoid problems of modifying an array that is being currently iterated through
$copy = $original;
foreach ($original as $key => $value)
{
//for each value evaluate if it is equivalent to the one to be deleted, and if it is capture its key name.
if($del_val === $value) $del_key[] = $key;
};
//If there was a value found, delete all its instances
if($del_key !== null)
{
foreach ($del_key as $dk_i)
{
unset($original[$dk_i]);
};
//optional reordering of the keys. WARNING: only use it with arrays with numeric indexes!
/*
$copy = $original;
$original = array();
foreach ($copy as $value) {
$original[] = $value;
};
*/
//the value was found and deleted
return true;
};
//The value was not found, nothing was deleted
return false;
};
$original = array(0,1,2,3,4,5,6,7,4);
$del_val = 4;
var_dump($original);
delete_value($original, $del_val);
var_dump($original);
Die Ausgabe wird sein:
array(9) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(2)
[3]=>
int(3)
[4]=>
int(4)
[5]=>
int(5)
[6]=>
int(6)
[7]=>
int(7)
[8]=>
int(4)
}
array(7) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(2)
[3]=>
int(3)
[5]=>
int(5)
[6]=>
int(6)
[7]=>
int(7)
}
1 Stimmen
@Adam Strudwick Aber wenn Sie viele Löschungen in diesem Array haben, wäre es dann besser, es einmal zu iterieren und den Schlüssel mit dem Wert gleichzusetzen?
1 Stimmen
Dieselbe Frage: stackoverflow.com/questions/1883421/
0 Stimmen
Mögliches Duplikat von PHP Löschen eines Elements aus einem Array