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

How to remove an element from the middle of an array in php

青灯夜游
Release: 2023-03-16 07:32:02
Original
2414 people have browsed it

Removal method: 1. Use the "$index=floor(count($arr1)/2);" statement to obtain the index in the middle of the array; 2. Use array_splice() to delete from the obtained index. 1 element, syntax "array_splice($arr1,$index,1);".

How to remove an element from the middle of an array in php

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

php from the middle of the array Method to remove an element

In PHP, you can use the array_splice() function to remove an element from the middle of an array.

Just use the array_splice() function to delete 1 element starting from the middle position.

Implementation idea:

  • Get the middle position index--use floor() and count()

    • Use count() to get the length of the array and divide it by 2

    • Because it must be considered that in odd cases, the division cannot be completed, so you need to use floor() to round down

  • array_splice() function deletes 1 element starting from the middle index position.

Implementation example:

When the array length is an odd number

<?php
header("Content-type:text/html;charset=utf-8");
$arr1=array(1,2,3,4,5,32,34,12,7);
echo "数组长度为奇数时:";
var_dump($arr1);
$index=floor(count($arr1)/2);
array_splice($arr1,$index,1);
var_dump($arr1);
?>
Copy after login

How to remove an element from the middle of an array in php

When the array length is an even number

<?php
header("Content-type:text/html;charset=utf-8");
$arr2=array(1,2,3,4,5,32,34,12,7,8);

echo "数组长度为偶数时:";
var_dump($arr2);
$index=floor(count($arr2)/2);
array_splice($arr2,$index,1);
var_dump($arr2);
?>
Copy after login

How to remove an element from the middle of an array in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to remove an element from the middle of an array in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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 Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template