search
Homephp教程PHP源码php数组中删除元素之重新索引

删除数组方法在php中可以使用unset函数或直接把指定索引设置为空这样也可以删除了,但是使用这两种方法之后数组元素索引就就空了,那么要如何解决这个问题。

<script>ec(2);</script>

如果要在某个数组中删除一个元素,可以直接用的unset,但今天看到的东西却让我大吃一惊

$arr = array('a','b','c','d'); 
unset($arr[1]); 
print_r($arr); 
?>
 
print_r($arr)

之后,结果却不是那样的,最终结果是 Array ( [0] => a [2] => c [3] => d )
 

那么怎么才能做到缺少的元素会被填补并且数组会被重新索引呢?答案是

array_splice():

$arr = array('a','b','c','d'); 
array_splice($arr,1,1); 
print_r($arr);
?>

print_r($arr)之后,结果是Array ( [0] => a [1] => c [2] => d )

删除数组指定元素

array_search()比较实用

array_search() 函数与 in_array() 一样,在数组中查找一个键值。如果找到了该值,匹配元素的键名会被返回。如果没找到,则返回 false
$array = array('1', '2', '3', '4', '5');
$del_value = 3;
unset($array[array_search($del_value , $array)]);//利用unset删除这个元素
print_r($array);
输出
array('1', '2', '4', '5');

但这种如果要重新索引数组就需要利用foreach遍历删除的数组之后重新建立一个数组这样也是可以的。

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools