Home >Backend Development >PHP Problem >How to remove the previous element of an array in php

How to remove the previous element of an array in php

青灯夜游
青灯夜游Original
2022-05-20 19:22:011713browse

Method: 1. Use "array_values($arr)" to convert the array into an index array; 2. Use "array_search(value, array)" to search for values ​​from the index array and return the corresponding index; 2. Use "array_splice($arr, index -1,1)" to delete the previous element from the original array.

How to remove the previous element of an array in php

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

php before removing the array Method of an element

1. Use array_values() to get the array key value and return the key value array

Use array_values() to convert the array Convert to an index array (make sure the array is an index array, so that you can get the position of the specified element in the array below).

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr = array("a" => "pear", "b" => "strawberry", "223", "c" => "cherry");
var_dump($arr);
$value=array_values($arr);
var_dump($value);
?>

How to remove the previous element of an array in php

2. Use array_search() to search for the specified value from the index array and return the corresponding index.

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr = array("a" => "pear", "b" => "strawberry", "223", "c" => "cherry");
var_dump($arr);
$value=array_values($arr);
var_dump($value);
$index=array_search("223",$value);
echo $index;
?>

How to remove the previous element of an array in php

##3. Use array_splice() to delete the previous element

According to the obtained element index, use array_splice() to delete the element at the "$index-1" position in the original array.

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr = array("a" => "pear", "b" => "strawberry", "223", "c" => "cherry");
var_dump($arr);
$value=array_values($arr);
var_dump($value);
$index=array_search("223",$value);
echo "指定元素的索引:".$index;
array_splice($arr,$index-1,1);
var_dump($arr);
?>

How to remove the previous element of an array in php

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of How to remove the previous element of 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