Skip to content
← Back to Snippets
Code

Using array_reduce()

Uses array_reduce() with a named callback to total numeric priority values.

Purpose

Uses array_reduce() with a named callback to total numeric priority 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.
 */

/**
 * Adds a mission priority value to the running total.
 *
 * @param int $carry Running total.
 * @param mixed $row Candidate row.
 * @return int New total.
 */
function ogSnippetArrayReducePriorityTotal(int $carry, $row): int {
	if (is_array($row) === false) {
		return $carry;
	}

	if (isset($row['priority']) === false) {
		return $carry;
	}

	return $carry + (int) $row['priority'];
}

/**
 * Using array_reduce().
 *
 * Purpose:
 * Reduces mission rows to one total priority number.
 *
 * @param array $missions Mission rows.
 * @return int Total priority.
 */
function ogSnippetUsingArrayReduce(array $missions): int {
	return array_reduce($missions, 'ogSnippetArrayReducePriorityTotal', 0);
}

$total_priority = ogSnippetUsingArrayReduce(array(
	array('name' => 'Tycho repair', 'priority' => 10),
	array('name' => 'Acheron sweep', 'priority' => 30)
));

echo 'Total priority: '.$total_priority;