Skip to content
← Back to Functions
Code

Array Dot Path Writer

Writes nested array values by dot path without overwriting unrelated branches.

Function signature

ogWriteDotPathValue(data, path, value, create_missing = true)

Categories

  • File and Upload Safety

Parameters

dataSource array.pathDot-delimited path to write.valueValue to place at the target path.create_missingWhether missing branches may be created.

Return value

Short public-safe status message.

  • data
  • path
  • written

Compatibility

Existing function name and call order preserved; metadata signature corrected to source.

Minimum PHP version: 7.4

Security notes

Validate request method, identity, permissions, and caller-owned allowlists before use; keep secrets and internal paths out of public output.

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

/**
 * Writes nested array values by dot path without overwriting unrelated branches.
 *
 * Primary use case: Transform imported data or configuration maps.
 * Typical inputs: array, dot path, value.
 * Typical output: updated array.
 *
 * Implementation note: Create missing branches only when approved by option.
 *
 * @param array $data Source array.
 * @param string $path Dot-delimited path to write.
 * @param mixed $value Value to place at the target path.
 * @param bool $create_missing Whether missing branches may be created.
 * @return array Structured result with updated data and path metadata.
 */
function ogWriteDotPathValue($data, $path, $value, $create_missing = true) {
	$result = array(
		'success' => false,
		'message' => '',
		'data' => array()
	);

	if (!is_array($data)) {
		$result['message'] = 'Data must be an array.';
		return $result;
	}

	$path = trim((string)$path);
	if (empty($path)) {
		$result['message'] = 'Path is required.';
		return $result;
	}

	$parts = explode('.', $path);
	$current = &$data;

	foreach ($parts as $index => $part) {
		$part = trim((string)$part);
		if ($part === '') {
			$result['message'] = 'Path contains an empty segment.';
			return $result;
		}

		$is_last = false;
		if ($index == count($parts) - 1) {
			$is_last = true;
		}

		if ($is_last) {
			$current[$part] = $value;
		} else {
			if (!array_key_exists($part, $current)) {
				if (!$create_missing) {
					$result['message'] = 'Path branch is missing.';
					return $result;
				}
				$current[$part] = array();
			}

			if (!is_array($current[$part])) {
				$result['message'] = 'Path branch is not an array.';
				return $result;
			}

			$current = &$current[$part];
		}
	}

	$result['success'] = true;
	$result['message'] = 'Path value written.';
	$result['data'] = array(
		'updated' => $data,
		'path' => $path
	);

	return $result;
}