Home >Backend Development >PHP Problem >How to delete the array value of the specified subscript in php

How to delete the array value of the specified subscript in php

青灯夜游
青灯夜游Original
2021-10-18 19:06:412843browse

php method to delete the specified subscript array value: 1. Use the unset() function, the syntax "unset($arr[specified subscript]);"; 2. Use the array_splice() function, the syntax "array_splice ($arr, specified subscript, 1)".

How to delete the array value of the specified subscript in php

The operating environment of this tutorial: Windows 7 system, PHP version 7.1, DELL G3 computer

PHP delete specified Target array value

Method 1: 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 element with index 2

<?php
$arr = array(1 => &#39;one&#39;, 2 => &#39;two&#39;, 3 => &#39;three&#39;);
echo &#39;<pre class="brush:php;toolbar:false">&#39;;

//删除下标为2的元素
unset($arr[2]);
print_r($arr);
?>

Output result:

Array
(
    [1] => one
    [3] => three
)

Method 2: Use array_splice() function

array_splice() function can be used to delete array elements of a specified length starting from a specified position.

You only need to set the second parameter of the function to the specified subscript, and set the third parameter to 1 (delete an element).

<?php
header("Content-type:text/html;charset=utf-8");
$arr = array(&#39;one&#39;,&#39;two&#39;,&#39;three&#39;,&#39;php&#39;);
echo &#39;<pre class="brush:php;toolbar:false">&#39;;

//删除下标为2的元素
array_splice($arr,2,1);
print_r($arr);
?>

Output results:

Array
(
    [0] => one
    [1] => two
    [2] => php
)

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to delete the array value of the specified subscript 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