Facebook Twitter Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    You are at:Home»Programming»PHP»How To Remove Specific Array Element in PHP

    How To Remove Specific Array Element in PHP

    By RahulOctober 30, 20202 Mins Read

    Q. How do I remove a specific element from an array using PHP.

    Advertisement

    In this tutorial, you will learn two PHP unset() and array_splice() methods to remove specific array elements.

    Using PHP unset() Function

    Use the PHP unset() function to delete an element from an array.

    Basically it is used to unset any variable in PHP. This function accept variable as argument and unset it.

    Example:

    1
    2
    3
    4
    <?php
      $arr = array("a" => "apple", "b" => "ball", "c" => "cat");
      unset($arr["b"]);
    ?>

    Output:

    array("a" => "Apple", "c" => "Cat")
    

    Another Example:

    1
    2
    3
    4
    5
    <?php
      $arr = array(1, 2, 3, 4, 5);
      unset($arr[3]);
      print_r($arr)
    ?>

    Output:

    Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
        [4] => 5
    )
    

    You can see the result array is not indexed. To overcome from this condition, you can use array_splice() PHP function described below.

    Using PHP array_splice() Function

    You can also use array_splice() function to remove specific array element. This function also can be used to replace array elements by passing array with update values.

    This function takes three parameters, an array, offset (where to start), and length (number of elements to be removed).

    Here is an example with array_splice() function:

    1
    2
    3
    4
    5
    <?php
      $arr = array(1, 2, 3, 4, 5);
      array_splice($arr, 2, 2);
      print_r($arr)
    ?>

    Output:

    Array
    (
        [0] => 1
        [1] => 2
        [2] => 5
    )
    

    You can see that the result array is re-indexed.

    Conclusion

    In this tutorial, you learned two PHP functions used to remove specific element from an array.

    array PHP
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    How to Install PHP 8.2-7.4 on RHEL & CentOS Stream 9

    Installing PHP on Pop!_OS

    How to Install PHP 8.x on Pop!_OS

    Managing Dependencies with Composer: A Beginner’s Guide

    Add A Comment

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • How to Install PHP 8.2-7.4 on RHEL & CentOS Stream 9
    • How to Install MySQL 8.0 on RHEL & CentOS Stream 9
    • How to Split Large Archives in Linux using the Command Line
    • System.out.println() Method in Java: A Beginner’s Guide
    • Split Command in Linux With Examples (Split Large Files)
    Facebook Twitter Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.