Skip to content

How To Remove Specific Array Element in PHP

Removing specific array element in php. How do I remove a specific element from an array using PHP. PHP remote array element.

Category
PHP
Versions & support
About PHP →
On this page

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

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:

Output:

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

Another Example:

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:

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.

Rahul

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top