Skip to content
← Back to Snippets
Code

Create and Access an Array

Creates an indexed array and an associative array, then reads values with explicit existence checks.

Purpose

Creates an indexed array and an associative array, then reads values with explicit existence checks.

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

/**
 * Create and Access an Array.
 *
 * Purpose:
 * Creates simple arrays and safely reads values from them.
 *
 * @return array Array access report.
 */
function ogSnippetCreateAndAccessAnArray(): array {
	$ships = array('Enterprise', 'Serenity', 'Rocinante');
	$captains = array(
		'enterprise' => 'Jean-Luc Picard',
		'serenity' => 'Malcolm Reynolds',
		'rocinante' => 'James Holden'
	);

	$first_ship = '';
	$serenity_captain = '';

	if (isset($ships[0]) === true) {
		$first_ship = $ships[0];
	}

	if (array_key_exists('serenity', $captains) === true) {
		$serenity_captain = $captains['serenity'];
	}

	return array(
		'ships' => $ships,
		'captains' => $captains,
		'first_ship' => $first_ship,
		'serenity_captain' => $serenity_captain
	);
}

$array_report = ogSnippetCreateAndAccessAnArray();

echo 'First ship: '.$array_report['first_ship'];