Skip to content
← Back to Snippets
Code

Get Array Length with count()

Counts array elements with count() and returns both the count and an empty-state flag.

Purpose

Counts array elements with count() and returns both the count and an empty-state flag.

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 Array Length with count().
 *
 * Purpose:
 * Counts values in an array and reports whether the array is empty.
 *
 * @param array $values Values to count.
 * @return array Count report.
 */
function ogSnippetGetArrayLengthWithCount(array $values): array {
	$total = count($values);
	$is_empty = false;

	if ($total === 0) {
		$is_empty = true;
	}

	return array(
		'total' => $total,
		'is_empty' => $is_empty
	);
}

$count_report = ogSnippetGetArrayLengthWithCount(array('Ripley', 'Hicks', 'Bishop'));

echo 'Marine count: '.$count_report['total'];