Class luya\yii\helpers\ArrayHelper

Inheritanceluya\yii\helpers\ArrayHelper » yii\helpers\BaseArrayHelper
Subclassesluya\helpers\ArrayHelper
Available since version1.0.0
Source Code https://github.com/luyadev/yii-helpers/blob/master/src/helpers/ArrayHelper.php

Helper methods when dealing with Arrays.

Extends the {{yii\helpers\ArrayHelper}} class by some usefull functions like:

  • {{luya\yii\helpers\ArrayHelper::toObject()}}
  • {{luya\yii\helpers\ArrayHelper::arrayUnshiftAssoc()}}
  • {{luya\yii\helpers\ArrayHelper::typeCast()}}
  • {{luya\yii\helpers\ArrayHelper::search()}}
  • {{luya\yii\helpers\ArrayHelper::searchColumn()}}
  • {{luya\yii\helpers\ArrayHelper::searchColumns()}}
  • {{luya\yii\helpers\ArrayHelper::generateRange()}}

Public Properties

Hide inherited properties

Property Type Description Defined By
$sensitiveDefaultKeys array An array with sensitive keys which are used if no keys will be passed to {{luya\yii\helpers\ArrayHelper::coverSensitiveValues()}}. luya\yii\helpers\ArrayHelper

Public Methods

Hide inherited methods

Method Description Defined By
arrayUnshiftAssoc() Prepend an assoc array item as first entry for a given array. luya\yii\helpers\ArrayHelper
combine() Helper method to generate an array with the same keys and values. luya\yii\helpers\ArrayHelper
coverSensitiveValues() Cover senstive values from a given list of keys. luya\yii\helpers\ArrayHelper
filter() Filters array according to rules specified. yii\helpers\BaseArrayHelper
generateRange() Generate an Array from a Rang with an appending optional Text. luya\yii\helpers\ArrayHelper
getColumn() Returns the values of a specified column in an array. yii\helpers\BaseArrayHelper
getValue() Retrieves the value of an array element or object property with the given key or property name. yii\helpers\BaseArrayHelper
htmlDecode() Decodes HTML entities into the corresponding characters in an array of strings. yii\helpers\BaseArrayHelper
htmlEncode() Encodes special characters in an array of strings into HTML entities. yii\helpers\BaseArrayHelper
index() Indexes and/or groups the array according to a specified key. yii\helpers\BaseArrayHelper
isAssociative() Returns a value indicating whether the given array is an associative array. yii\helpers\BaseArrayHelper
isIn() Check whether an array or Traversable contains an element. yii\helpers\BaseArrayHelper
isIndexed() Returns a value indicating whether the given array is an indexed array. yii\helpers\BaseArrayHelper
isSubset() Checks whether an array or Traversable is a subset of another array or Traversable. yii\helpers\BaseArrayHelper
isTraversable() Checks whether a variable is an array or Traversable. yii\helpers\BaseArrayHelper
keyExists() Checks if the given array contains the specified key. yii\helpers\BaseArrayHelper
map() Builds a map (key-value pairs) from a multidimensional array or an array of objects. yii\helpers\BaseArrayHelper
merge() Merges two or more arrays into one recursively. yii\helpers\BaseArrayHelper
multisort() Sorts an array of objects or arrays (with the same structure) by one or several keys. yii\helpers\BaseArrayHelper
recursiveSort() Sorts array recursively. yii\helpers\BaseArrayHelper
remove() Removes an item from an array and returns the value. If the key does not exist in the array, the default value will be returned instead. yii\helpers\BaseArrayHelper
removeValue() Removes items with matching values from the array and returns the removed items. yii\helpers\BaseArrayHelper
search() Search trough all keys inside of an array, any occurence will return the rest of the array. luya\yii\helpers\ArrayHelper
searchColumn() Search for a Column Value inside a Multidimension array and return the array with the found key. luya\yii\helpers\ArrayHelper
searchColumns() Search for columns with the given search value, returns the full array with all valid items. luya\yii\helpers\ArrayHelper
setValue() Writes a value into an associative array at the key path specified. yii\helpers\BaseArrayHelper
toArray() Converts an object or an array of objects into an array. yii\helpers\BaseArrayHelper
toObject() Create an object from an array. luya\yii\helpers\ArrayHelper
typeCast() TypeCast values from a mixed array source. numeric values will be casted as integer. luya\yii\helpers\ArrayHelper

Property Details

Hide inherited properties

$sensitiveDefaultKeys public static property

An array with sensitive keys which are used if no keys will be passed to {{luya\yii\helpers\ArrayHelper::coverSensitiveValues()}}.

public static array $sensitiveDefaultKeys = [
    
'password',
    
'pwd',
    
'pass',
    
'passwort',
    
'pw',
    
'token',
    
'hash',
    
'authorization',
    
'auth',
]

Method Details

Hide inherited methods

arrayUnshiftAssoc() public static method

Prepend an assoc array item as first entry for a given array.

Adds the given key with value as first entry to $arr

public static array arrayUnshiftAssoc ( &$arr, $key, $val )
$arr array

The array where the value should be prepend

$key string

The new array key

$val mixed

The value for the new key

                public static function arrayUnshiftAssoc(&$arr, $key, $val)
{
    $arr = array_reverse($arr, true);
    $arr[$key] = $val;
    return array_reverse($arr, true);
}

            
combine() public static method

Helper method to generate an array with the same keys and values.

$data = ArrayHelper::combine(['foo', 'bar']);

// generates
['foo' => 'foo', 'bar' => 'bar'];
public static array combine ( array $array )
$array array

The array to combine.

                public static function combine(array $array)
{
    return array_combine($array, $array);
}

            
coverSensitiveValues() public static method

Cover senstive values from a given list of keys.

The main purpose is to remove passwords transferd to api when existing in post, get or session.

Example:

$data = ArrayHelper::coverSensitiveValues(['username' => 'foo', 'password' => 'bar'], ['password']];

var_dump($data); // array('username' => 'foo', 'password' => '***');
public static void coverSensitiveValues ( array $data, array $keys = [] )
$data array

The input data to cover given sensitive key values. ['username' => 'foo', 'password' => 'bar'].

$keys array

The keys which can contain sensitive data inside the $data array. ['password', 'pwd', 'pass'] if no keys provided the {{luya\yii\helpers\ArrayHelper::$sensitiveDefaultKeys}} is used.

                public static function coverSensitiveValues(array $data, array $keys = [])
{
    if (empty($keys)) {
        $keys = self::$sensitiveDefaultKeys;
    }
    $clean = [];
    foreach ($keys as $key) {
        $kw = strtolower($key);
        foreach ($data as $k => $v) {
            if (is_array($v)) {
                $clean[$k] = static::coverSensitiveValues($v, $keys);
            } elseif (is_scalar($v) && ($kw == strtolower($k) || StringHelper::startsWith(strtolower($k), $kw))) {
                $v = str_repeat("*", strlen($v));
                $clean[$k] = $v;
            }
        }
    }
    // the later overrides the former
    return array_replace($data, $clean);
}

            
filter() public static method (available since version 2.0.9)

Defined in: yii\helpers\BaseArrayHelper::filter()

Filters array according to rules specified.

For example:

$array = [
    'A' => [1, 2],
    'B' => [
        'C' => 1,
        'D' => 2,
    ],
    'E' => 1,
];

$result = \yii\helpers\ArrayHelper::filter($array, ['A']);
// $result will be:
// [
//     'A' => [1, 2],
// ]

$result = \yii\helpers\ArrayHelper::filter($array, ['A', 'B.C']);
// $result will be:
// [
//     'A' => [1, 2],
//     'B' => ['C' => 1],
// ]

$result = \yii\helpers\ArrayHelper::filter($array, ['B', '!B.C']);
// $result will be:
// [
//     'B' => ['D' => 2],
// ]
public static array filter ( $array, $filters )
$array array

Source array

$filters iterable

Rules that define array keys which should be left or removed from results. Each rule is:

  • var - $array['var'] will be left in result.
  • var.key = only `$array['var']['key'] will be left in result.
  • !var.key = `$array['var']['key'] will be removed from result.
return array

Filtered array

                public static function filter($array, $filters)
{
    $result = [];
    $excludeFilters = [];
    foreach ($filters as $filter) {
        if (!is_string($filter) && !is_int($filter)) {
            continue;
        }
        if (is_string($filter) && strncmp($filter, '!', 1) === 0) {
            $excludeFilters[] = substr($filter, 1);
            continue;
        }
        $nodeValue = $array; //set $array as root node
        $keys = explode('.', (string) $filter);
        foreach ($keys as $key) {
            if (!array_key_exists($key, $nodeValue)) {
                continue 2; //Jump to next filter
            }
            $nodeValue = $nodeValue[$key];
        }
        //We've found a value now let's insert it
        $resultNode = &$result;
        foreach ($keys as $key) {
            if (!array_key_exists($key, $resultNode)) {
                $resultNode[$key] = [];
            }
            $resultNode = &$resultNode[$key];
        }
        $resultNode = $nodeValue;
    }
    foreach ($excludeFilters as $filter) {
        $excludeNode = &$result;
        $keys = explode('.', (string) $filter);
        $numNestedKeys = count($keys) - 1;
        foreach ($keys as $i => $key) {
            if (!array_key_exists($key, $excludeNode)) {
                continue 2; //Jump to next filter
            }
            if ($i < $numNestedKeys) {
                $excludeNode = &$excludeNode[$key];
            } else {
                unset($excludeNode[$key]);
                break;
            }
        }
    }
    return $result;
}

            
generateRange() public static method

Generate an Array from a Rang with an appending optional Text.

This is commonly used when generate dropDowns in forms to select a number of something.

When $text is an array, the first key is the singular value to use, the second is the pluralized value.

$range = ArrayHelper::generateRange(1, 3, 'ticket');
// array (1 => "1 ticket", 2 => "2 ticket", 3 => "3 ticket")

Using the pluralized texts:

$range = ArrayHelper::generateRange(1, 3, ['ticket', 'tickets']);
// array (1 => "1 ticket", 2 => "2 tickets", 3 => "3 tickets")

In php range() function is used to generate the array range.

public static array generateRange ( $from, $to, $text null )
$from string|integer

The range starts from

$to string|integer

The range ends

$text string|array

Optinal text to append to each element. If an array is given the first value is used for the singular value, the second will be used for the pluralized values.

return array

An array where the key is the number and value the number with optional text.

                public static function generateRange($from, $to, $text = null)
{
    $range = range($from, $to);
    $array = array_combine($range, $range);
    if ($text) {
        array_walk($array, function (&$item, $key) use ($text) {
            if (is_array($text)) {
                list($singular, $plural) = $text;
                if ($key == 1) {
                    $item = "{$key} {$singular}";
                } else {
                    $item = "{$key} {$plural}";
                }
            } else {
                $item = "{$key} {$text}";
            }
        });
    }
    return $array;
}

            
getColumn() public static method

Defined in: yii\helpers\BaseArrayHelper::getColumn()

Returns the values of a specified column in an array.

The input array should be multidimensional or an array of objects.

For example,

$array = [
    ['id' => '123', 'data' => 'abc'],
    ['id' => '345', 'data' => 'def'],
];
$result = ArrayHelper::getColumn($array, 'id');
// the result is: ['123', '345']

// using anonymous function
$result = ArrayHelper::getColumn($array, function ($element) {
    return $element['id'];
});
public static array getColumn ( $array, $name, $keepKeys true )
$array array
$name integer|string|array|Closure
$keepKeys boolean

Whether to maintain the array keys. If false, the resulting array will be re-indexed with integers.

return array

The list of column values

                public static function getColumn($array, $name, $keepKeys = true)
{
    $result = [];
    if ($keepKeys) {
        foreach ($array as $k => $element) {
            $result[$k] = static::getValue($element, $name);
        }
    } else {
        foreach ($array as $element) {
            $result[] = static::getValue($element, $name);
        }
    }
    return $result;
}

            
getValue() public static method

Defined in: yii\helpers\BaseArrayHelper::getValue()

Retrieves the value of an array element or object property with the given key or property name.

If the key does not exist in the array, the default value will be returned instead. Not used when getting value from an object.

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,

// 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']);
public static mixed getValue ( $array, $key, $default null )
$array array|object

Array or object to extract value from

$key string|Closure|array

Key name of the array element, an array of keys or property name of the object, or an anonymous function returning the value. The anonymous function signature should be: function($array, $defaultValue). The possibility to pass an array of keys is available since version 2.0.4.

$default mixed

The default value to be returned if the specified array key does not exist. Not used when getting value from an object.

return mixed

The value of the element if found, default value otherwise

                public static function getValue($array, $key, $default = null)
{
    if ($key instanceof \Closure) {
        return $key($array, $default);
    }
    if (is_array($key)) {
        $lastKey = array_pop($key);
        foreach ($key as $keyPart) {
            $array = static::getValue($array, $keyPart);
        }
        $key = $lastKey;
    }
    if (is_object($array) && property_exists($array, $key)) {
        return $array->$key;
    }
    if (static::keyExists($key, $array)) {
        return $array[$key];
    }
    if ($key && ($pos = strrpos($key, '.')) !== false) {
        $array = static::getValue($array, substr($key, 0, $pos), $default);
        $key = substr($key, $pos + 1);
    }
    if (static::keyExists($key, $array)) {
        return $array[$key];
    }
    if (is_object($array)) {
        // this is expected to fail if the property does not exist, or __get() is not implemented
        // it is not reliably possible to check whether a property is accessible beforehand
        try {
            return $array->$key;
        } catch (\Exception $e) {
            if ($array instanceof ArrayAccess) {
                return $default;
            }
            throw $e;
        }
    }
    return $default;
}

            
htmlDecode() public static method

Defined in: yii\helpers\BaseArrayHelper::htmlDecode()

Decodes HTML entities into the corresponding characters in an array of strings.

Only array values will be decoded by default. If a value is an array, this method will also decode it recursively. Only string values will be decoded.

See also https://www.php.net/manual/en/function.htmlspecialchars-decode.php.

public static array htmlDecode ( $data, $valuesOnly true )
$data array

Data to be decoded

$valuesOnly boolean

Whether to decode array values only. If false, then both the array keys and array values will be decoded.

return array

The decoded data

                public static function htmlDecode($data, $valuesOnly = true)
{
    $d = [];
    foreach ($data as $key => $value) {
        if (!$valuesOnly && is_string($key)) {
            $key = htmlspecialchars_decode($key, ENT_QUOTES | ENT_SUBSTITUTE);
        }
        if (is_string($value)) {
            $d[$key] = htmlspecialchars_decode($value, ENT_QUOTES | ENT_SUBSTITUTE);
        } elseif (is_array($value)) {
            $d[$key] = static::htmlDecode($value, $valuesOnly);
        } else {
            $d[$key] = $value;
        }
    }
    return $d;
}

            
htmlEncode() public static method

Defined in: yii\helpers\BaseArrayHelper::htmlEncode()

Encodes special characters in an array of strings into HTML entities.

Only array values will be encoded by default. If a value is an array, this method will also encode it recursively. Only string values will be encoded.

See also https://www.php.net/manual/en/function.htmlspecialchars.php.

public static array htmlEncode ( $data, $valuesOnly true, $charset null )
$data array

Data to be encoded

$valuesOnly boolean

Whether to encode array values only. If false, both the array keys and array values will be encoded.

$charset string|null

The charset that the data is using. If not set, yii\base\Application::$charset will be used.

return array

The encoded data

                public static function htmlEncode($data, $valuesOnly = true, $charset = null)
{
    if ($charset === null) {
        $charset = Yii::$app ? Yii::$app->charset : 'UTF-8';
    }
    $d = [];
    foreach ($data as $key => $value) {
        if (!$valuesOnly && is_string($key)) {
            $key = htmlspecialchars($key, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
        }
        if (is_string($value)) {
            $d[$key] = htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
        } elseif (is_array($value)) {
            $d[$key] = static::htmlEncode($value, $valuesOnly, $charset);
        } else {
            $d[$key] = $value;
        }
    }
    return $d;
}

            
index() public static method

Defined in: yii\helpers\BaseArrayHelper::index()

Indexes and/or groups the array according to a specified key.

The input should be either multidimensional array or an array of objects.

The $key can be either a key name of the sub-array, a property name of object, or an anonymous function that must return the value that will be used as a key.

$groups is an array of keys, that will be used to group the input array into one or more sub-arrays based on keys specified.

If the $key is specified as null or a value of an element corresponding to the key is null in addition to $groups not specified then the element is discarded.

For example:

$array = [
    ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
    ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
    ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
];
$result = ArrayHelper::index($array, 'id');

The result will be an associative array, where the key is the value of id attribute

[
    '123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
    '345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
    // The second element of an original array is overwritten by the last element because of the same id
]

An anonymous function can be used in the grouping array as well.

$result = ArrayHelper::index($array, function ($element) {
    return $element['id'];
});

Passing id as a third argument will group $array by id:

$result = ArrayHelper::index($array, null, 'id');

The result will be a multidimensional array grouped by id on the first level, by device on the second level and indexed by data on the third level:

[
    '123' => [
        ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
    ],
    '345' => [ // all elements with this index are present in the result array
        ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
        ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
    ]
]

The anonymous function can be used in the array of grouping keys as well:

$result = ArrayHelper::index($array, 'data', [function ($element) {
    return $element['id'];
}, 'device']);

The result will be a multidimensional array grouped by id on the first level, by the device on the second one and indexed by the data on the third level:

[
    '123' => [
        'laptop' => [
            'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
        ]
    ],
    '345' => [
        'tablet' => [
            'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet']
        ],
        'smartphone' => [
            'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
        ]
    ]
]
public static array index ( $array, $key, $groups = [] )
$array array

The array that needs to be indexed or grouped

$key string|Closure|null

The column name or anonymous function which result will be used to index the array

$groups string|string[]|Closure[]|null

The array of keys, that will be used to group the input array by one or more keys. If the $key attribute or its value for the particular element is null and $groups is not defined, the array element will be discarded. Otherwise, if $groups is specified, array element will be added to the result array without any key. This parameter is available since version 2.0.8.

return array

The indexed and/or grouped array

                public static function index($array, $key, $groups = [])
{
    $result = [];
    $groups = (array) $groups;
    foreach ($array as $element) {
        $lastArray = &$result;
        foreach ($groups as $group) {
            $value = static::getValue($element, $group);
            if (!array_key_exists($value, $lastArray)) {
                $lastArray[$value] = [];
            }
            $lastArray = &$lastArray[$value];
        }
        if ($key === null) {
            if (!empty($groups)) {
                $lastArray[] = $element;
            }
        } else {
            $value = static::getValue($element, $key);
            if ($value !== null) {
                if (is_float($value)) {
                    $value = StringHelper::floatToString($value);
                }
                $lastArray[$value] = $element;
            }
        }
        unset($lastArray);
    }
    return $result;
}

            
isAssociative() public static method

Defined in: yii\helpers\BaseArrayHelper::isAssociative()

Returns a value indicating whether the given array is an associative array.

An array is associative if all its keys are strings. If $allStrings is false, then an array will be treated as associative if at least one of its keys is a string.

Note that an empty array will NOT be considered associative.

public static boolean isAssociative ( $array, $allStrings true )
$array array

The array being checked

$allStrings boolean

Whether the array keys must be all strings in order for the array to be treated as associative.

return boolean

Whether the array is associative

                public static function isAssociative($array, $allStrings = true)
{
    if (empty($array) || !is_array($array)) {
        return false;
    }
    if ($allStrings) {
        foreach ($array as $key => $value) {
            if (!is_string($key)) {
                return false;
            }
        }
        return true;
    }
    foreach ($array as $key => $value) {
        if (is_string($key)) {
            return true;
        }
    }
    return false;
}

            
isIn() public static method (available since version 2.0.7)

Defined in: yii\helpers\BaseArrayHelper::isIn()

Check whether an array or Traversable contains an element.

This method does the same as the PHP function in_array() but additionally works for objects that implement the Traversable interface.

See also https://www.php.net/manual/en/function.in-array.php.

public static boolean isIn ( $needle, $haystack, $strict false )
$needle mixed

The value to look for.

$haystack iterable

The set of values to search.

$strict boolean

Whether to enable strict (===) comparison.

return boolean

true if $needle was found in $haystack, false otherwise.

throws yii\base\InvalidArgumentException

if $haystack is neither traversable nor an array.

                public static function isIn($needle, $haystack, $strict = false)
{
    if (!static::isTraversable($haystack)) {
        throw new InvalidArgumentException('Argument $haystack must be an array or implement Traversable');
    }
    if (is_array($haystack)) {
        return in_array($needle, $haystack, $strict);
    }
    foreach ($haystack as $value) {
        if ($strict ? $needle === $value : $needle == $value) {
            return true;
        }
    }
    return false;
}

            
isIndexed() public static method

Defined in: yii\helpers\BaseArrayHelper::isIndexed()

Returns a value indicating whether the given array is an indexed array.

An array is indexed if all its keys are integers. If $consecutive is true, then the array keys must be a consecutive sequence starting from 0.

Note that an empty array will be considered indexed.

public static boolean isIndexed ( $array, $consecutive false )
$array array

The array being checked

$consecutive boolean

Whether the array keys must be a consecutive sequence in order for the array to be treated as indexed.

return boolean

Whether the array is indexed

                public static function isIndexed($array, $consecutive = false)
{
    if (!is_array($array)) {
        return false;
    }
    if (empty($array)) {
        return true;
    }
    $keys = array_keys($array);
    if ($consecutive) {
        return $keys === array_keys($keys);
    }
    foreach ($keys as $key) {
        if (!is_int($key)) {
            return false;
        }
    }
    return true;
}

            
isSubset() public static method (available since version 2.0.7)

Defined in: yii\helpers\BaseArrayHelper::isSubset()

Checks whether an array or Traversable is a subset of another array or Traversable.

This method will return true, if all elements of $needles are contained in $haystack. If at least one element is missing, false will be returned.

public static boolean isSubset ( $needles, $haystack, $strict false )
$needles iterable

The values that must all be in $haystack.

$haystack iterable

The set of value to search.

$strict boolean

Whether to enable strict (===) comparison.

return boolean

true if $needles is a subset of $haystack, false otherwise.

throws yii\base\InvalidArgumentException

if $haystack or $needles is neither traversable nor an array.

                public static function isSubset($needles, $haystack, $strict = false)
{
    if (!static::isTraversable($needles)) {
        throw new InvalidArgumentException('Argument $needles must be an array or implement Traversable');
    }
    foreach ($needles as $needle) {
        if (!static::isIn($needle, $haystack, $strict)) {
            return false;
        }
    }
    return true;
}

            
isTraversable() public static method (available since version 2.0.8)

Defined in: yii\helpers\BaseArrayHelper::isTraversable()

Checks whether a variable is an array or Traversable.

This method does the same as the PHP function is_array() but additionally works on objects that implement the Traversable interface.

See also https://www.php.net/manual/en/function.is-array.php.

public static boolean isTraversable ( $var )
$var mixed

The variable being evaluated.

return boolean

Whether $var can be traversed via foreach

                public static function isTraversable($var)
{
    return is_array($var) || $var instanceof Traversable;
}

            
keyExists() public static method

Defined in: yii\helpers\BaseArrayHelper::keyExists()

Checks if the given array contains the specified key.

This method enhances the array_key_exists() function by supporting case-insensitive key comparison.

public static boolean keyExists ( $key, $array, $caseSensitive true )
$key string

The key to check

$array array|ArrayAccess

The array with keys to check

$caseSensitive boolean

Whether the key comparison should be case-sensitive

return boolean

Whether the array contains the specified key

                public static function keyExists($key, $array, $caseSensitive = true)
{
    if ($caseSensitive) {
        // Function `isset` checks key faster but skips `null`, `array_key_exists` handles this case
        // https://www.php.net/manual/en/function.array-key-exists.php#107786
        if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) {
            return true;
        }
        // Cannot use `array_has_key` on Objects for PHP 7.4+, therefore we need to check using [[ArrayAccess::offsetExists()]]
        return $array instanceof ArrayAccess && $array->offsetExists($key);
    }
    if ($array instanceof ArrayAccess) {
        throw new InvalidArgumentException('Second parameter($array) cannot be ArrayAccess in case insensitive mode');
    }
    foreach (array_keys($array) as $k) {
        if (strcasecmp($key, $k) === 0) {
            return true;
        }
    }
    return false;
}

            
map() public static method

Defined in: yii\helpers\BaseArrayHelper::map()

Builds a map (key-value pairs) from a multidimensional array or an array of objects.

The $from and $to parameters specify the key names or property names to set up the map. Optionally, one can further group the map according to a grouping field $group.

For example,

$array = [
    ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
    ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
    ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
];

$result = ArrayHelper::map($array, 'id', 'name');
// the result is:
// [
//     '123' => 'aaa',
//     '124' => 'bbb',
//     '345' => 'ccc',
// ]

$result = ArrayHelper::map($array, 'id', 'name', 'class');
// the result is:
// [
//     'x' => [
//         '123' => 'aaa',
//         '124' => 'bbb',
//     ],
//     'y' => [
//         '345' => 'ccc',
//     ],
// ]
public static array map ( $array, $from, $to, $group null )
$array array
$from string|Closure
$to string|Closure
$group string|Closure|null

                public static function map($array, $from, $to, $group = null)
{
    $result = [];
    foreach ($array as $element) {
        $key = static::getValue($element, $from);
        $value = static::getValue($element, $to);
        if ($group !== null) {
            $result[static::getValue($element, $group)][$key] = $value;
        } else {
            $result[$key] = $value;
        }
    }
    return $result;
}

            
merge() public static method

Defined in: yii\helpers\BaseArrayHelper::merge()

Merges two or more arrays into one recursively.

If each array has an element with the same string key value, the latter will overwrite the former (different from array_merge_recursive). Recursive merging will be conducted if both arrays have an element of array type and are having the same key. For integer-keyed elements, the elements from the latter array will be appended to the former array. You can use yii\helpers\UnsetArrayValue object to unset value from previous array or yii\helpers\ReplaceArrayValue to force replace former value instead of recursive merging.

public static array merge ( $a, $b )
$a array

Array to be merged to

$b array

Array to be merged from. You can specify additional arrays via third argument, fourth argument etc.

return array

The merged array (the original arrays are not changed.)

                public static function merge($a, $b)
{
    $args = func_get_args();
    $res = array_shift($args);
    while (!empty($args)) {
        foreach (array_shift($args) as $k => $v) {
            if ($v instanceof UnsetArrayValue) {
                unset($res[$k]);
            } elseif ($v instanceof ReplaceArrayValue) {
                $res[$k] = $v->value;
            } elseif (is_int($k)) {
                if (array_key_exists($k, $res)) {
                    $res[] = $v;
                } else {
                    $res[$k] = $v;
                }
            } elseif (is_array($v) && isset($res[$k]) && is_array($res[$k])) {
                $res[$k] = static::merge($res[$k], $v);
            } else {
                $res[$k] = $v;
            }
        }
    }
    return $res;
}

            
multisort() public static method

Defined in: yii\helpers\BaseArrayHelper::multisort()

Sorts an array of objects or arrays (with the same structure) by one or several keys.

public static void multisort ( &$array, $key, $direction SORT_ASC, $sortFlag SORT_REGULAR )
$array array

The array to be sorted. The array will be modified after calling this method.

$key string|Closure|array

The key(s) to be sorted by. This refers to a key name of the sub-array elements, a property name of the objects, or an anonymous function returning the values for comparison purpose. The anonymous function signature should be: function($item). To sort by multiple keys, provide an array of keys here.

$direction integer|array

The sorting direction. It can be either SORT_ASC or SORT_DESC. When sorting by multiple keys with different sorting directions, use an array of sorting directions.

$sortFlag integer|array

The PHP sort flag. Valid values include SORT_REGULAR, SORT_NUMERIC, SORT_STRING, SORT_LOCALE_STRING, SORT_NATURAL and SORT_FLAG_CASE. Please refer to PHP manual for more details. When sorting by multiple keys with different sort flags, use an array of sort flags.

throws yii\base\InvalidArgumentException

if the $direction or $sortFlag parameters do not have correct number of elements as that of $key.

                public static function multisort(&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR)
{
    $keys = is_array($key) ? $key : [$key];
    if (empty($keys) || empty($array)) {
        return;
    }
    $n = count($keys);
    if (is_scalar($direction)) {
        $direction = array_fill(0, $n, $direction);
    } elseif (count($direction) !== $n) {
        throw new InvalidArgumentException('The length of $direction parameter must be the same as that of $keys.');
    }
    if (is_scalar($sortFlag)) {
        $sortFlag = array_fill(0, $n, $sortFlag);
    } elseif (count($sortFlag) !== $n) {
        throw new InvalidArgumentException('The length of $sortFlag parameter must be the same as that of $keys.');
    }
    $args = [];
    foreach ($keys as $i => $k) {
        $flag = $sortFlag[$i];
        $args[] = static::getColumn($array, $k);
        $args[] = $direction[$i];
        $args[] = $flag;
    }
    // This fix is used for cases when main sorting specified by columns has equal values
    // Without it it will lead to Fatal Error: Nesting level too deep - recursive dependency?
    $args[] = range(1, count($array));
    $args[] = SORT_ASC;
    $args[] = SORT_NUMERIC;
    $args[] = &$array;
    call_user_func_array('array_multisort', $args);
}

            
recursiveSort() public static method

Defined in: yii\helpers\BaseArrayHelper::recursiveSort()

Sorts array recursively.

public static array recursiveSort ( array &$array, $sorter null )
$array array

An array passing by reference.

$sorter callable|null

The array sorter. If omitted, sort index array by values, sort assoc array by keys.

                public static function recursiveSort(array &$array, $sorter = null)
{
    foreach ($array as &$value) {
        if (is_array($value)) {
            static::recursiveSort($value, $sorter);
        }
    }
    unset($value);
    if ($sorter === null) {
        $sorter = static::isIndexed($array) ? 'sort' : 'ksort';
    }
    call_user_func_array($sorter, [&$array]);
    return $array;
}

            
remove() public static method

Defined in: yii\helpers\BaseArrayHelper::remove()

Removes an item from an array and returns the value. If the key does not exist in the array, the default value will be returned instead.

Usage examples,

// $array = ['type' => 'A', 'options' => [1, 2]];
// working with array
$type = \yii\helpers\ArrayHelper::remove($array, 'type');
// $array content
// $array = ['options' => [1, 2]];
public static mixed|null remove ( &$array, $key, $default null )
$array array

The array to extract value from

$key string

Key name of the array element

$default mixed

The default value to be returned if the specified key does not exist

return mixed|null

The value of the element if found, default value otherwise

                public static function remove(&$array, $key, $default = null)
{
    if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) {
        $value = $array[$key];
        unset($array[$key]);
        return $value;
    }
    return $default;
}

            
removeValue() public static method (available since version 2.0.11)

Defined in: yii\helpers\BaseArrayHelper::removeValue()

Removes items with matching values from the array and returns the removed items.

Example,

$array = ['Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', 'Janet' => 'Jackson'];
$removed = \yii\helpers\ArrayHelper::removeValue($array, 'Jackson');
// result:
// $array = ['Bob' => 'Dylan', 'Mick' => 'Jagger'];
// $removed = ['Michael' => 'Jackson', 'Janet' => 'Jackson'];
public static array removeValue ( &$array, $value )
$array array

The array where to look the value from

$value mixed

The value to remove from the array

return array

The items that were removed from the array

                public static function removeValue(&$array, $value)
{
    $result = [];
    if (is_array($array)) {
        foreach ($array as $key => $val) {
            if ($val === $value) {
                $result[$key] = $val;
                unset($array[$key]);
            }
        }
    }
    return $result;
}

            
search() public static method

Search trough all keys inside of an array, any occurence will return the rest of the array.

$data  = [
    ['name' => 'Foo Bar', 'id' => 1],
    ['name' => 'Bar Baz', 'id' => 2],
];

Assuming the above array the expression ArrayHelper::search($data, 1) would return:

$data  = [
    ['name' => 'Foo Bar', 'id' => 1],
];

Searching for the string Bar would return the the orignal array is bar would be found in both.

In order to search only in certain keys defined $keys attribute:

ArrayHelper::search($data, 'Foo', false, ['name']);

The above example will search only in the array key name for the Foo expression.

public static array search ( array $array, $searchText, $sensitive false, array $keys = [] )
$array array

The multidimensional array keys.

$searchText string

The text you where search inside the rows.

$sensitive boolean

Whether to use strict sensitive search (true) or case insenstivie search (false).

$keys array

A list of array keys which should be taken to search in, if empty or not provided it will lookup all array keys by default.

return array

The modified array depending on the search result hits.

                public static function search(array $array, $searchText, $sensitive = false, array $keys = [])
{
    $function = $sensitive ? 'strpos' : 'stripos';
    return array_filter($array, function ($item) use ($searchText, $function, $keys) {
        $response = false;
        foreach ($item as $key => $value) {
            if ($response) {
                continue;
            }
            if (!empty($keys) && !in_array($key, $keys)) {
                continue;
            }
            if ($function($value, "$searchText") !== false) {
                $response = true;
            }
        }
        return $response;
    });
}

            
searchColumn() public static method

Search for a Column Value inside a Multidimension array and return the array with the found key.

Compare to searchColumns() this function return will return the first found result.

$array = [
    ['name' => 'luya', 'userId' => 1],
    ['name' => 'nadar', 'userId' => 2],
];

$result = ArrayHelper::searchColumn($array, 'name', 'nadar');

// output:
// array ('name' => 'nadar', 'userId' => 2);

This will not work with assoc keys

public static array|boolean searchColumn ( array $array, $column, $search )
$array array

The array with the multimensional array values.

$column string

The column to lookup and compare with the $search string.

$search string

The string to search inside the provided column.

                public static function searchColumn(array $array, $column, $search)
{
    $array = array_values($array); // align array keys
    $columns = array_column($array, $column);
    $key = array_search($search, $columns);
    return ($key !== false) ? $array[$key] : false;
}

            
searchColumns() public static method

Search for columns with the given search value, returns the full array with all valid items.

Compare to searchColumn() this function return will return all found results.

This function is not casesensitive, which means FOO will match Foo, foo and FOO

$array = [
    ['name' => 'luya', 'userId' => 1],
    ['name' => 'nadar', 'userId' => 1],
];

$result = ArrayHelper::searchColumns($array, 'userId', '1');

// output:
// array (
//     array ('name' => 'luya', 'userId' => 1),
//     array ('name' => 'nadar', 'userId' => 1)
// );
public static array searchColumns ( array $array, $column, $search )
$array array

The multidimensional array input

$column string

The column to compare with $search string

$search mixed

The search string to compare with the column value.

return array

Returns an array with all valid elements.

                public static function searchColumns(array $array, $column, $search)
{
    $keys = array_filter($array, function ($var) use ($column, $search) {
        return strcasecmp($search, (string) $var[$column]) == 0 ? true : false;
    });
    return $keys;
}

            
setValue() public static method (available since version 2.0.13)

Defined in: yii\helpers\BaseArrayHelper::setValue()

Writes a value into an associative array at the key path specified.

If there is no such key path yet, it will be created recursively. If the key exists, it will be overwritten.

 $array = [
     'key' => [
         'in' => [
             'val1',
             'key' => 'val'
         ]
     ]
 ];

The result of ArrayHelper::setValue($array, 'key.in.0', ['arr' => 'val']); will be the following:

 [
     'key' => [
         'in' => [
             ['arr' => 'val'],
             'key' => 'val'
         ]
     ]
 ]

The result of ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']); or ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']); will be the following:

 [
     'key' => [
         'in' => [
             'arr' => 'val'
         ]
     ]
 ]
public static void setValue ( &$array, $path, $value )
$array array

The array to write the value to

$path string|array|null

The path of where do you want to write a value to $array the path can be described by a string when each key should be separated by a dot you can also describe the path as an array of keys if the path is null then $array will be assigned the $value

$value mixed

The value to be written

                public static function setValue(&$array, $path, $value)
{
    if ($path === null) {
        $array = $value;
        return;
    }
    $keys = is_array($path) ? $path : explode('.', $path);
    while (count($keys) > 1) {
        $key = array_shift($keys);
        if (!isset($array[$key])) {
            $array[$key] = [];
        }
        if (!is_array($array[$key])) {
            $array[$key] = [$array[$key]];
        }
        $array = &$array[$key];
    }
    $array[array_shift($keys)] = $value;
}

            
toArray() public static method

Defined in: yii\helpers\BaseArrayHelper::toArray()

Converts an object or an array of objects into an array.

public static array toArray ( $object, $properties = [], $recursive true )
$object object|array|string

The object to be converted into an array

$properties array

A mapping from object class names to the properties that need to put into the resulting arrays. The properties specified for each class is an array of the following format:

[
    'app\models\Post' => [
        'id',
        'title',
        // the key name in array result => property name
        'createTime' => 'created_at',
        // the key name in array result => anonymous function
        'length' => function ($post) {
            return strlen($post->content);
        },
    ],
]

The result of ArrayHelper::toArray($post, $properties) could be like the following:

[
    'id' => 123,
    'title' => 'test',
    'createTime' => '2013-01-01 12:00AM',
    'length' => 301,
]
$recursive boolean

Whether to recursively converts properties which are objects into arrays.

return array

The array representation of the object

                public static function toArray($object, $properties = [], $recursive = true)
{
    if (is_array($object)) {
        if ($recursive) {
            foreach ($object as $key => $value) {
                if (is_array($value) || is_object($value)) {
                    $object[$key] = static::toArray($value, $properties, true);
                }
            }
        }
        return $object;
    } elseif ($object instanceof \DateTimeInterface) {
        return (array)$object;
    } elseif (is_object($object)) {
        if (!empty($properties)) {
            $className = get_class($object);
            if (!empty($properties[$className])) {
                $result = [];
                foreach ($properties[$className] as $key => $name) {
                    if (is_int($key)) {
                        $result[$name] = $object->$name;
                    } else {
                        $result[$key] = static::getValue($object, $name);
                    }
                }
                return $recursive ? static::toArray($result, $properties) : $result;
            }
        }
        if ($object instanceof Arrayable) {
            $result = $object->toArray([], [], $recursive);
        } else {
            $result = [];
            foreach ($object as $key => $value) {
                $result[$key] = $value;
            }
        }
        return $recursive ? static::toArray($result, $properties) : $result;
    }
    return [$object];
}

            
toObject() public static method

Create an object from an array.

public static object toObject ( array $array )
$array array

                public static function toObject(array $array)
{
    return json_decode(json_encode($array), false, 512);
}

            
typeCast() public static method

TypeCast values from a mixed array source. numeric values will be casted as integer.

This method is often used to convert corect json respons arrays

public static array typeCast ( array $array )
$array array

The array which should be type casted

return array

An array with type casted values

                public static function typeCast(array $array)
{
    $return = [];
    foreach ($array as $k => $v) {
        if (is_numeric($v)) {
            $return[$k] = StringHelper::typeCastNumeric($v);
        } elseif (is_array($v)) {
            $return[$k] = self::typeCast($v);
        } else {
            $return[$k] = $v;
        }
    }
    return $return;
}