Home>Article>Backend Development> How to delete the 5th element in an array in php

How to delete the 5th element in an array in php

青灯夜游
青灯夜游 Original
2022-05-10 19:24:32 2266browse

2 methods: 1. Use array_splice(), just set the second parameter to 4 and the third parameter to 1, the syntax is "array_splice($arr,4,1)". 2. Use unset(), the syntax "unset($arr[4])" is suitable for index arrays, and delete the element with index 4.

How to delete the 5th element in an array in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php delete array Method for the 5th element

Method 1: Use array_splice() function

array_splice() function can start from the specified position and delete the specified number of array elements.

You only need to set the starting position to 4 and the number of deletions to 1 to delete the 5th element (starting after the 4th element).

Example:

How to delete the 5th element in an array in php

"red","b"=>"green","c"=>"blue","d"=>"1","e"=>"2","f"=>"3"); var_dump($arr); //删除第5个元素 array_splice($arr,4,1); var_dump($arr); ?>

How to delete the 5th element in an array in php

##2. Use the unset() function

If you want to delete an element in the array, you can use unset().

The unset() function allows you to cancel elements in an array, but the array will not re-index, that is, the original index will be maintained, because the index in PHP has a special meaning.

Example: Delete the 5th element (element with index 4)


How to delete the 5th element in an array in php

Instructions:

The array_splice() method is suitable for indexed arrays and associative arrays.

The unset() method is suitable for index arrays; in associative arrays, you need to get the string key name of the fifth element first, and then delete the element based on the key name, but this is too troublesome.

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of How to delete the 5th element in an array 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