xxxxxxxxxx
$colors = array("blue","green","red");
//delete element in array by value "green"
if (($key = array_search("green", $colors)) !== false) {
unset($colors[$key]);
}
xxxxxxxxxx
<?php
$arr = array('Sam','Kin','Alex','Dineal');
if(in_array('Sam',$arr)){
unset($arr[array_search('Sam',$arr)]);
}
print_r($arr);
?>
Array
(
[1] => Kin
[2] => Alex
[3] => Dineal
)
xxxxxxxxxx
if (($key = array_search($value, $sampleArray)) !== false) {
unset($sampleArray[$key]);
}
xxxxxxxxxx
// matrix array
foreach($appsList as $key => $app) {
if($app["app_status"] !== "approved") {
// remove orange apps
unset($appsList[$key]);
}
}
xxxxxxxxxx
//TL;DR
// Most Handy and One Line Solution:
$arr = array_merge(array_diff($arr, array("yellow", "red")));
// Detailed Answer Below
// Our initial array
$arr = array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red");
print_r($arr);
// Remove the elements who's values are yellow or red
$arr = array_diff($arr, array("yellow", "red"));
print_r($arr);
// OUTPUT
Array
(
[0] => blue
[1] => green
[2] => red
[3] => yellow
[4] => green
[5] => orange
[6] => yellow
[7] => indigo
[8] => red
)
Array
(
[0] => blue
[1] => green
[4] => green
[5] => orange
[7] => indigo
)
Now, array_values() will reindex a numerical array nicely,
but it will remove all key strings from the array and replace them with numbers.
If you need to preserve the key names (strings),
or reindex the array if all keys are numerical, use array_merge():
// Code
$arr = array_merge(array_diff($arr, array("yellow", "red")));
print_r($arr);
// OUTPUT
Array
(
[0] => blue
[1] => green
[2] => green
[3] => orange
[4] => indigo
)
xxxxxxxxxx
if (($key = array_search($del_val, $messages)) !== false) {
unset($messages[$key]);
}
xxxxxxxxxx
array_diff( [312, 401, 15, 401, 3], [401] ) // removing 401 returns [312, 15, 3]
xxxxxxxxxx
$colors = arrray("blue","green","red");
if(($key = array_search("greeb",$colors)) !== false)
{
unset("$colors[$key]);
}