温馨提示×

php怎么删除数组中指定元素

PHP
小亿
82
2024-02-05 10:07:35
栏目: 编程语言

在PHP中,可以使用unset()函数来删除数组中的指定元素。下面是一个例子:

$fruits = array("apple", "banana", "orange", "grape");

// 删除数组中的第二个元素(下标为1)
unset($fruits[1]);

// 打印结果
print_r($fruits);

输出结果为:

Array
(
    [0] => apple
    [2] => orange
    [3] => grape
)

注意,使用unset()函数删除数组元素时,会保留原数组的索引。如果要重新索引数组,可以使用array_values()函数。例如:

$fruits = array_values($fruits);
print_r($fruits);

输出结果为:

Array
(
    [0] => apple
    [1] => orange
    [2] => grape
)

0