PHP array is a set of data collection, to organize a series of data to form an operational whole, a lot of development needs to use, then this article introduces several ways to delete the specified value elements in PHP array, we most likely to think of the unset after the foreach traversal is deleted, So what's the other way?
This is a test array $testArr = array ( ' t ' = = ' qq ', ' q ' = ' qq ', ' b ' = ' Baidu ', ' a ' = ' Ali '), ' m ' = ' Xiaomi ' );
Method One:
This method is also the easiest way to think of the unset delete after the foreach traversal function Delbyvalue ($arr, $value) { if (!is_array ($arr)) { return $ arr; } foreach ($arr as $k = + $v) { if ($v = = $value) { unset ($arr [$k]);} } return $arr; }
Method Two:
Array_flip after the unset, this method has a disadvantage, that is, after the reversal because there are two key values are QQ, there is a data will be lost, so please be careful when using the function Delbyvalue ($arr, $value) { $TEMPARR = Array_flip ($arr); Unset ($TEMPARR [$value]); Return Array_flip ($TEMPARR); }
Method Three:
Array_search, this method also has the disadvantage, array_search search to a suitable value to return, so there are multiple related values in the array this method does not apply) function Delbyvalue ($arr, $value) { $key = Array_search ($value, $arr); if (Isset ($key)) { unset ($arr [$key]); } return $arr; }
Method Four:
Use Array_keys to search for the specified value recirculation unset) function Delbyvalue ($arr, $value) { $keys = Array_keys ($arr, $value); Var_dump ($keys); if (!empty ($keys)) { foreach ($keys as $key) { unset ($arr [$key]); } } return $arr; }
The above four methods method one and method four is better, think which method is more preferable, then have your own decision.