Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Chương trình PHP xóa phần tử khỏi mảng với unset()

Ví dụ

<?php
$my_array = array("Joe", "Ben", "Mary", "Barun", "Sona", "Mona");
unset($my_array[4]);
print_r("After deleting the element, the array is ");
print_r($my_array);
?>

Kết quả

After deleting the element, the array is
Array (
    [0] => Joe
    [1] => Ben
    [2] => Mary
    [3] => Barun
    [5] => Mona
)

Giải thích

Mảng được định nghĩa với nhiều chuỗi:

$my_array = array("Joe", "Ben", "Mary", "Barun", "Sona", "Mona");

Hàm unset() xóa phần tử tại index chỉ định (index 4 là "Sona"). Sau khi xóa, mảng in ra. Lưu ý: Key index 4 bị xóa, key 5 vẫn giữ nguyên (không re-index tự động).

unset($my_array[4]);
print_r("After deleting the element, the array is ");
print_r($my_array);

Mẹo: Dùng array_values() để re-index mảng sau khi unset.