Skip to content
← Back to Snippets
Code

Using array_filter()

Uses array_filter() with a named callback to keep only non-empty scalar values.

Purpose

Uses array_filter() with a named callback to keep only non-empty scalar values.

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

/**
 * Checks whether a value should remain after filtering.
 *
 * @param mixed $value Candidate value.
 * @return bool Whether to keep the value.
 */
function ogSnippetArrayFilterKeepFilledScalar($value): bool {
	if (is_scalar($value) === false) {
		return false;
	}

	if (trim((string) $value) === '') {
		return false;
	}

	return true;
}

/**
 * Using array_filter().
 *
 * Purpose:
 * Filters an array with a named callback.
 *
 * @param array $values Values to filter.
 * @return array Filtered and reindexed values.
 */
function ogSnippetUsingArrayFilter(array $values): array {
	$filtered = array_filter($values, 'ogSnippetArrayFilterKeepFilledScalar');

	return array_values($filtered);
}

$filtered = ogSnippetUsingArrayFilter(array('Ripley', '', 'Hicks', array('ignored')));

echo 'Filtered count: '.count($filtered);