Skip to content
← Back to Snippets
Code

Get Difference Between Two Arrays

Returns values from the first array that do not appear in the second array, using strict scalar comparison.

Purpose

Returns values from the first array that do not appear in the second array, using strict scalar comparison.

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.
 */

/**
 * Get Difference Between Two Arrays.
 *
 * Purpose:
 * Finds scalar values present in the first array but absent from the second.
 *
 * @param array $first First value list.
 * @param array $second Values to exclude.
 * @return array Difference values.
 */
function ogSnippetGetArrayDifference(array $first, array $second): array {
	$difference = array();

	foreach ($first as $value) {
		if (is_scalar($value) === false) {
			continue;
		}

		if (in_array($value, $second, true) === false) {
			$difference[] = $value;
		}
	}

	return $difference;
}

$available_ships = ogSnippetGetArrayDifference(array('Enterprise', 'Defiant', 'Voyager'), array('Voyager'));

echo 'Available ships: '.count($available_ships);