PHP 配列から要素を削除する関数


末尾の要素を削除

<?php
    $fruits = array("apple", "banana", "orange");

    $fruit = array_pop($fruits);

    echo $fruit; #=> orange

    print_r($fruits);
    /*
    Array
    (
        [0] => apple
        [1] => banana
    )
    */
?>


先頭の要素を削除

<?php
    $fruits = array("apple", "banana", "orange");

    $fruit = array_shift($fruits);

    echo $fruit; #=> apple

    print_r($fruits);
    /*
    Array
    (
        [0] => banana
        [1] => orange
    )
    */
?>


重複している要素を削除

<?php
    $fruits = array("apple", "banana", "orange", "banana", "orange");

    print_r(array_unique($fruits));
    /*
    Array
    (
        [0] => apple
        [1] => banana
        [2] => orange
    )
    */

    $fruits2 = array("apple", "apple", "orange", "orange");

    print_r(array_unique($fruits2));
    /*
    Array
    (
        [0] => apple
        [2] => orange
    )
    */
?>


範囲内の要素を削除

<?php
    $fruits = array("apple", "banana", "orange", "kiwi");

    $input1 = $fruits;

    # [1]以降を削除
    array_splice($input1, 1);

    print_r($input1);
    /*
    Array
    (
        [0] => apple
    )
    */

    $input2 = $fruits;

    #=> [1]から[2]まで削除
    array_splice($input2, 1, 2);

    print_r($input2);
    /*
    Array
    (
        [0] => apple
        [1] => kiwi
    )
    */

    $input3 = $fruits;

    #=> -1は最後の一つ前
    array_splice($input3, 1, -1);

    print_r($input3);
    /*
    Array
    (
        [0] => apple
        [1] => kiwi
    )
    */
?>