If the key does not exist in the array or object, the default value will be returned instead.
The key may be specified in a dot format to retrieve the value of a sub-array or the property
of an embedded object. In particular, if the key is x.y.z, then the returned value would
be $array['x']['y']['z'] or $array->x->y->z (if $array is an object). If $array['x']
or $array->x is neither an array nor an object, the default value will be returned.
Note that if the array already has an element x.y.z, then its value will be returned
instead of going through the sub-arrays. So it is better to be done specifying an array of key names
like ['x', 'y', 'z'].
Below are some usage examples,
php
working with array
$username = \yii\helpers\ArrayHelper::getValue($_POST, 'username');
working with object
$username = \yii\helpers\ArrayHelper::getValue($user, 'username');
working with anonymous function
$fullName = \yii\helpers\ArrayHelper::getValue($user, function ($user, $defaultValue) {
return $user->firstName . ' ' . $user->lastName;
});
using dot format to retrieve the property of embedded object
$street = \yii\helpers\ArrayHelper::getValue($users, 'address.street');
using an array of keys to retrieve the value
$value = \yii\helpers\ArrayHelper::getValue($versions, ['1.0', 'date']);