Reputation: 12190
How can I remove element that starts with TOR example key [27].
Array
(
[1] => memory_target
[2] => vif_2_rx
[3] => vif_2_tx
[4] => memory
[5] => vbd_xvda_read
[6] => vbd_xvda_write
[7] => vbd_xvdd_read
[8] => vbd_xvdd_write
[9] => vif_1_rx
[10] => vif_1_tx
[11] => vif_0_rx
[12] => vif_0_tx
[13] => cpu0
[27] => TOR-SRV65
)
This is what I have tried so far.
if(($key = array_search($del_val, $messages)) !== false) {
unset($messages[$key]);
}
But haven't been able to get it to work!
Upvotes: 1
Views: 1594
Reputation: 6169
I am using this function to delete a key from array
function removeValueFromArray($array, $key, $value){
foreach($array as $subKey => $subArray){
if($subArray[$key] == $value){
unset($array[$subKey]);
}
}
return $array;
}
This function remove the key from array based on certain value and return final array
Upvotes: 0
Reputation: 59681
You can simply array_filter()
the elements out which have TOR
at the start like this:
$messages = array_filter($messages, function($v){
return !(substr(trim($v), 0, 3) === "TOR");
});
Case insensitive version:
$messages = array_filter($messages, function($v){
return !(strtoupper(substr(trim($v), 0, 3)) === "TOR");
});
EDIT:
Even simpler with preg_grep()
(Remove the modifier i
if you want it case sensitive):
$messages = preg_grep ("/[^\bTOR]/i", array_map("trim", $messages));
Upvotes: 1
Reputation: 5500
Try:
$array = array(
'memory_target',
'vif_2_rx',
'TOR-SRV65'
);
foreach ($array as $key => $value) {
if (strtolower(substr($value, 0, 3)) == 'tor') {
unset($array[$key]);
}
}
print_r($array); // Output => Array ( [0] => memory_target [1] => vif_2_rx )
Upvotes: 0