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
Release: 2024-12-16 01:14:09
Original
558 people have browsed it

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, ...];
Copy after login

To delete the element with the value 401:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template