Home > Backend Development > PHP Problem > How to delete an element in an array in php

How to delete an element in an array in php

PHPz
Release: 2023-04-20 10:58:51
Original
581 people have browsed it

In PHP, array is a very common data type. When we need to delete an element in the array, we can use the array_splice() or unset() function to achieve this.

  1. Using the array_splice() function

The array_splice() function removes elements of a specified length from an array and replaces them with another set of values. If replacement is not required, the replacement value parameter can be omitted. You can use the array_splice() function according to the following syntax:

array_splice($array, $start, $length, $replacement);
Copy after login

Among them, $array is the array that needs to be operated, $start is the starting position, that is, the position of the element to be deleted, $length is the number of elements to be deleted, $replacement is the element to be replaced (optional).

For example, the following code deletes the element with index 2 in the array $arr:

$arr = array('a', 'b', 'c', 'd', 'e');
array_splice($arr, 2, 1);
print_r($arr);
Copy after login

The output result is as follows:

Array
(
    [0] => a
    [1] => b
    [2] => d
    [3] => e
)
Copy after login
  1. Use the unset() function

The unset() function is used to release variables or array elements. The syntax is as follows:

unset($array[$key]);
Copy after login

Among them, $array is the array that needs to be operated, and $key is the key name of the element that needs to be deleted.

For example, the following code deletes the element with key name 2 in array $arr:

$arr = array('a', 'b', 'c', 'd', 'e');
unset($arr[2]);
print_r($arr);
Copy after login

The output result is as follows:

Array
(
    [0] => a
    [1] => b
    [3] => d
    [4] => e
)
Copy after login

Summary

array_splice () function and unset() function can delete elements in the array. If you need to change the length of the array, you can use the array_splice() function. If you only need to remove elements without changing the length of the array, you can use the unset() function.

The above is the detailed content of How to delete an element in an array 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template