3v4l.org

run code in 300+ PHP versions simultaneously
<?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
Output for 7.1.26 - 7.1.33, 7.2.17 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.27, 8.4.1 - 8.4.14
Peter 5th somedefaultvalue 12

preferences:
161.29 ms | 407 KiB | 5 Q