Skip to content
← Back to Snippets
Code

Loop Through an Array with foreach

Loops through an indexed array with `foreach`, normalizes each ship record, and returns numbered display rows without assuming every element is valid.

Purpose

Loops through an indexed array with `foreach`, normalizes each ship record, and returns numbered display rows without assuming every element is valid.

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

/**
 * Loop Through an Array with foreach.
 *
 * Purpose:
 * Demonstrates a readable `foreach` loop over an array of records while
 * checking each row before preparing display output.
 *
 * @param array $ship_manifest Indexed list of ship records.
 * @return array Numbered display rows and skipped row count.
 */
function ogSnippetLoopThroughArrayWithForeach(array $ship_manifest): array {
	$display_rows = array();
	$skipped_rows = 0;
	$row_number = 1;

	foreach ($ship_manifest as $manifest_entry) {
		if (is_array($manifest_entry) === false) {
			$skipped_rows++;
			continue;
		}

		if (isset($manifest_entry['ship']) === false || isset($manifest_entry['status']) === false) {
			$skipped_rows++;
			continue;
		}

		$ship_name = trim((string) $manifest_entry['ship']);
		$ship_status = trim((string) $manifest_entry['status']);

		if ($ship_name === '' || $ship_status === '') {
			$skipped_rows++;
			continue;
		}

		$display_rows[] = $row_number.'. '.htmlspecialchars($ship_name, ENT_QUOTES, 'UTF-8').' — '.htmlspecialchars($ship_status, ENT_QUOTES, 'UTF-8');
		$row_number++;
	}

	return array(
		'rows' => $display_rows,
		'skipped_rows' => $skipped_rows
	);
}

$colonial_manifest = array(
	array('ship' => 'Galactica', 'status' => 'combat air patrol active'),
	array('ship' => 'Rocinante', 'status' => 'burn schedule locked'),
	array('ship' => 'Serenity', 'status' => 'cargo bay sealed')
);

$manifest_report = ogSnippetLoopThroughArrayWithForeach($colonial_manifest);

foreach ($manifest_report['rows'] as $display_row) {
	echo $display_row."
";
}