I have a PHP array as follows:
$messages = [312, 401, 1599, 3, ...];
I want to delete the element containing the value $del_val
If you know for definite that your array will contain only one element with that value, you can do
$key = array_search($del_val, $array);
if (false !== $key) {
unset($array[$key]);
}
If, however, your value might occur more than once in your array, you could do this
$array = array_filter($array, function($e) use ($del_val) {
return ($e !== $del_val);
});
Note: The second option only works for PHP5.3+ with Closures
To delete multiple values try this one:
while (($key = array_search($del_val, $messages)) !== false)
{
unset($messages[$key]);
}
As per your requirement "each value can only be there for once" if you are just interested in keeping unique values in your array, then the array_unique() might be what you are looking for.
Input:
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
Result:
array(2) {
[0] => int(4)
[2] => string(1) "3"
}
function array_remove_by_value($array, $value)
{
return array_values(array_diff($array, array($value)));
}
$array = array(312, 401, 1599, 3);
$newarray = array_remove_by_value($array, 401);
print_r($newarray);
Output
Array ( [0] => 312 [1] => 1599 [2] => 3 )
$fields = array_flip($fields);
unset($fields['myvalue']);
$fields = array_flip($fields);
here is one simple but understandable solution:
$messagesFiltered = [];
foreach ($messages as $message) {
if (401 != $message) {
$messagesFiltered[] = $message;
}
}
$messages = $messagesFiltered;