P粉5117578482023-08-21 13:42:03
Use array_diff()
for a one-line solution:
$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi', 'strawberry'); //再加一个'strawberry'以证明它可以删除字符串的多个实例 $array_without_strawberries = array_diff($array, array('strawberry')); print_r($array_without_strawberries);
...No need for extra functions or foreach loops.
P粉2540777472023-08-21 12:54:10
Use the array_search
function to get the key and the unset
function to remove it if found:
if (($key = array_search('strawberry', $array)) !== false) { unset($array[$key]); }The
array_search
function returns false when no item is found (returns null before PHP 4.2.0).
If there may be multiple items with the same value, you can use the array_keys
function to get the keys of all items:
foreach (array_keys($array, 'strawberry') as $key) { unset($array[$key]); }