<?php $customer = ['name' => 'Peter', 'address' => ['street' => '5th', 'number' => 1969]]; /** * @param array $array * @param string $path A dot-separated property path. * @param mixed $default * @return mixed */ function getArrayValue(array $array, string $path, $default = null) { $parts = explode('.', $path); return array_reduce($parts, static function ($value, $part) use ($default) { return $value[$part] ?? $default; }, $array); } /** * @param string $path A dot-separated path, whose first part is a var name available in the global scope. * @param mixed $default * @return mixed */ function getGlobalArrayValue(string $path, $default = null) { @list($varName, $propertyPath) = explode('.', $path, 2); return getArrayValue($GLOBALS[$varName] ?? [], $propertyPath, $default); } echo getGlobalArrayValue('customer.name'), PHP_EOL; // Peter echo getGlobalArrayValue('customer.address.street'), PHP_EOL; // '5th' echo getGlobalArrayValue('customer.address.idontexist', 'somedefaultvalue'), PHP_EOL; // 'somedefaultvalue' echo getGlobalArrayValue('idontexist.address', 12); // 12
You have javascript disabled. You will not be able to edit any code.