Last Update - 02 Aug 2019

Remove a specific item from an array in PHP

Remove a specific item from an array in PHP

Some ask for a more-specific post about removing items from your code, here’s an easy way to remove a specific element from a PHP array by key instead of index.

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 unsetting that key.

More For You

Did you find this page helpful? X