Skip to content
← Back to Snippets
Code

Remove Last Element from Array with array_pop()

Removes the last value from an indexed array with array_pop() and returns both the removed value and the remaining list.

Purpose

Removes the last value from an indexed array with array_pop() and returns both the removed value and the remaining list.

Snippet details

ContextArrayLevelPracticalCopy-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 Last Element from Array with array_pop().
 *
 * Purpose:
 * Removes and returns the final value from an indexed array.
 *
 * @param array $crew_queue Indexed queue values.
 * @return array Removed value and remaining queue.
 */
function ogSnippetArrayPop(array $crew_queue): array {
	$queue = array();

	foreach ($crew_queue as $crew_member) {
		if (is_scalar($crew_member) === true) {
			$crew_member = trim((string) $crew_member);

			if ($crew_member !== '') {
				$queue[] = $crew_member;
			}
		}
	}

	$removed = '';

	if (count($queue) > 0) {
		$removed = array_pop($queue);
	}

	return array(
		'removed' => $removed,
		'remaining' => $queue,
		'remaining_count' => count($queue)
	);
}

$pop_report = ogSnippetArrayPop(array('Adama', 'Starbuck', 'Apollo'));

echo 'Removed crew member: '.$pop_report['removed'];