How to remove an element from an array in PHP

Today, we will explain to you how to remove an element from an array in PHP. There are multiple ways to remove an element from an array in PHP but here we’ll show you the two ways with examples.

Similar articles

Ways to remove an element from an Array

  1. unset() function
  2. array_splice() function

1. unset() function

In the below example, you can see how to use unset() function to remove the element from an array.

Example 1

You can see in the above output array which is not reindexed after removing the element from an array. So we can use the array_values() functions to get a re-indexed array.

To remove key/values from the associative array, you can use unset() function as shown in the following example.

Example 2

Here, we have a student array and we will remove the branch key and its value from an array.

2. array_splice() function

In an alternative way, you can use array_splice() function to remove the specific element from an array.

Syntax

Parameters

  • $array (Required): Specifies an original array.
  • $start (Required) : Specifies the offset where to start removing the element.
  • $length (Optional): Specifies the number of elements to be removed. If this value is not set, the function will remove all the values starting from the $start parameter.
  • $newarray (Optional): Specifies an array with elements which we want to insert into the original array.

Example

Here, you can see the above output array is re-indexed.

That’s it for today.
Thank you for reading. Happy Coding..!!

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

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