You could include this in your project
https://github.com/rappasoft/laravel-helpers/blob/master/src/helpers.php
or use this variety
if ( ! function_exists('array_get'))
{
/**
* Get an item from an array using "dot" notation.
*
* @param array $array
* @param string $key
* @param mixed $default
* @return mixed
*/
function array_get($array, $key, $default = null)
{
if (is_null($key)) return $array;
if (isset($array[$key])) return $array[$key];
foreach (explode('.', $key) as $segment)
{
if ( ! is_array($array) || ! array_key_exists($segment, $array))
{
return $default;
}
$array = $array[$segment];
}
return $array;
}
}
What it does is split the string by dot (.
) and then try to fetch the elmenents that in that array. so if you'd do array_get($array, 'foo'); it would be as if you'd type $array['foo'].
But if the variable is set in the array, it will return it's value.
null is a valid value, but not one you're likely to find in a $_POST array.
But if you also wish to filter out the null values I do recommend using a manual check instead of a catch all. Sometimes you want that null.
But if you need a function for it I suggest modifying the above function to
if ( ! function_exists('array_get'))
{
/**
* Get an item from an array using "dot" notation.
*
* @param array $array
* @param string $key
* @param mixed $default
* @return mixed
*/
function array_get($array, $key, $default = null)
{
if (is_null($key)) return $array;
if (isset($array[$key])) {
$value = $array[$key];
/**
* Here is the null check. You can also add empty checks and other checks.
*/
if(is_null($value)) {
return $default;
}
return $value
}
foreach (explode('.', $key) as $segment)
{
if ( ! is_array($array) || ! array_key_exists($segment, $array))
{
return $default;
}
$array = $array[$segment];
}
return $array;
}
}
Then you can simply use
array_get($_POST,'abc','some default value');
That way you don't have to worry if it's intantiated or not.
Added bonus is, if you have nested arrays, this makes it easy to access them without having to worry if the lower arrays are initiated or not.
$arr = ['foo' => ['bar' => ['baz' => 'Hello world']]];
array_get($arr, 'foo.bar.baz', 'The world has ended');
array_get($arr, 'foo.bar.ouch', 'The world has ended');