php数组中删除元素之重新索引,php数组元素索引
如果要在某个数组中删除一个元素,可以直接用的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)之后,结果是A(www.111cn.net)rray ( [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遍历删除的数组之后重新建立一个数组这样也是可以的。
来自php教程网:http://www.111cn.net/phper/php-cy/66372.htm
array_values() 返回 input 数组中所有的值并给其建立数字索引。
array_value($arr['date']);
unset($arr[1]);

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
