Remove a specific element from an array PHP

Remove a specific element from an array PHP

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

Removing items from your array by value, here’s an easy way to remove a specific element from a PHP array by key instead of index.

Using unset() function

Use the PHP unset() function to delete an element from an array. The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy.

Using array_search() function

If the array contains only a single element with the specified value, you can use the array_search() function with unset() function to remove it from an array.

function my_remove_array_item( $array, $item ) {
	$index = array_search($item, $array);
	if ( $index !== false ) {
		unset( $array[$index] );
	}
	return $array;
}

Usage:

$items = array( 'first', 'second', 'third');
$items = my_remove_array_item( $items, 'second' ); // remove item called 'second'

This works by searching the array for the specified item, returning its key, and then unset that key.

Related posts
Write a comment