Skip to content
← Back to Snippets
Code

Remove Element from an Array

Removes all exact strict matches from an array and reindexes the result.

Purpose

Removes all exact strict matches from an array and reindexes the result.

Snippet details

ContextArrayLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Forms and Validation

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Remove Element from an Array.
 *
 * Purpose:
 * Removes matching values from an array using strict comparison.
 *
 * @param array $values Source values.
 * @param string $remove_value Value to remove.
 * @return array Reindexed values without the removed value.
 */
function ogSnippetRemoveElementFromArray(array $values, string $remove_value): array {
	$filtered = array();

	foreach ($values as $value) {
		if ($value === $remove_value) {
			continue;
		}

		$filtered[] = $value;
	}

	return $filtered;
}

$contacts = array('Cylon', 'Colonial', 'Cylon');
$contacts = ogSnippetRemoveElementFromArray($contacts, 'Cylon');

echo 'Remaining contacts: '.count($contacts);