Home >Backend Development >PHP Tutorial >How to Delete Array Elements by Value in PHP?

How to Delete Array Elements by Value in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-16 01:14:09554browse

How to Delete Array Elements by Value in PHP?

Deleting Array Elements by Value in PHP

In PHP, arrays are indexed by keys, typically integers or strings. However, situations may arise where you need to remove an element from an array based on its value rather than its key. This can be achieved by utilizing the array_search() function in conjunction with unset().

Using array_search() and unset()

To delete an array element by value, follow these steps:

  1. Use array_search($del_val, $messages) to retrieve the key of the element with the value you want to remove.
  2. Store the key in a variable, such as $key.
  3. Use unset($messages[$key]) to delete the element with that key from the array.

Example:

Given an array $messages containing unique values:

$messages = [312, 401, 1599, 3, ...];

To delete the element with the value 401:

if (($key = array_search(401, $messages)) !== false) {
    unset($messages[$key]);
}

Explanation:

  • array_search(401, $messages) returns the key (index) of the element with the value 401.
  • The if() statement checks if array_search() returned a valid key (not FALSE).
  • If a key is found, unset($messages[$key]) is executed, which removes the element from the array.

Note:

  • array_search() requires the values in the array to be unique.
  • array_search() returns FALSE on failure or false-y values on success (e.g., key 0), hence the strict comparison !== false in the if() statement.

The above is the detailed content of How to Delete Array Elements by Value in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn