Delete an Element From an Array in PHP

In this tutorial, we are going to check how to delete elements from an array in PHP.

We can use unset() function to delete a specific index of an array.

CONTENTS

Steps to delete an element from an array using unset()

Suppose you have an array i.e $array = [ 'delete', 'an', 'element', 'from', 'an', 'array' ];. You want to remove the item 'element' from it. You need to pass the index number of that specific element i.e. ‘element’. In our case, it is 2.

<?php
	
	$array = [ 'delete', 'an', 'element', 'from', 'an', 'array' ];
	unset( $array[2] );
	var_dump( $array );

The output will be:

array (size=5)
  0 => string 'delete' (length=6)
  1 => string 'an' (length=2)
  3 => string 'from' (length=4)
  4 => string 'an' (length=2)
  5 => string 'array' (length=5)

You can also delete multiple elements from an array by passing multiple variables into unset().

<?php
	
$array = [ 'delete', 'an', 'element', 'from', 'an', 'array' ];

unset( $array[1], $array[3], $array[4] );

var_dump( $array );

The output will be:

array (size=3)
  0 => string 'delete' (length=6)
  2 => string 'element' (length=7)
  5 => string 'array' (length=5)

But the problem is, if you want to print the Deleted Element Index from that array again, it will show an error.

<?php
	
$array = [ 'delete', 'an', 'element', 'from', 'an', 'array' ];
unset( $array[1], $array[3], $array[4] );
echo $array[1];

The output will be:

Notice: Undefined offset: 1

To get rid of this error, we need to reindex the array.

How to reindex an array after deleting element from it?

In order to re-index the array, we can use PHP array_values() function.

<?php
	
$array = [ 'delete', 'an', 'element', 'from', 'an', 'array' ];
unset( $array[1], $array[3], $array[4] );

$array = array_values( $array );

var_dump($array);

The output will be:

array (size=3)
  0 => string 'delete' (length=6)
  1 => string 'element' (length=7)
  2 => string 'array' (length=5)

Delete an array element based on key

To remove the element from an associative array, you can simply pass the key to unset().

<?php
	
$user = array(
	"name"		=> "John",
	"address"	=> "NY",
	"age"		=> "35",
);
unset($user['address']);

var_dump($user);

Output:

array (size=2)
  'name' => string 'John' (length=4)
  'age' => string '35' (length=2)

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment