3 * This file is part of the array_column library
5 * For the full copyright and license information, please view the LICENSE
6 * file that was distributed with this source code.
8 * @copyright Copyright (c) Ben Ramsey (http://benramsey.com)
9 * @license http://opensource.org/licenses/MIT MIT
12 if (!function_exists('array_column')) {
14 * Returns the values from a single column of the input array, identified by
17 * Optionally, you may provide an $indexKey to index the values in the returned
18 * array by the values from the $indexKey column in the input array.
20 * @param array $input A multi-dimensional array (record set) from which to pull
22 * @param mixed $columnKey The column of values to return. This value may be the
23 * integer key of the column you wish to retrieve, or it
24 * may be the string key name for an associative array.
25 * @param mixed $indexKey (Optional.) The column to use as the index/keys for
26 * the returned array. This value may be the integer key
27 * of the column, or it may be the string key name.
30 function array_column($input = null, $columnKey = null, $indexKey = null)
32 // Using func_get_args() in order to check for proper number of
33 // parameters and trigger errors exactly as the built-in array_column()
35 $argc = func_num_args();
36 $params = func_get_args();
39 trigger_error("array_column() expects at least 2 parameters, {$argc} given", E_USER_WARNING
);
43 if (!is_array($params[0])) {
45 'array_column() expects parameter 1 to be array, ' . gettype($params[0]) . ' given',
51 if (!is_int($params[1])
52 && !is_float($params[1])
53 && !is_string($params[1])
54 && $params[1] !== null
55 && !(is_object($params[1]) && method_exists($params[1], '__toString'))
57 trigger_error('array_column(): The column key should be either a string or an integer', E_USER_WARNING
);
62 && !is_int($params[2])
63 && !is_float($params[2])
64 && !is_string($params[2])
65 && !(is_object($params[2]) && method_exists($params[2], '__toString'))
67 trigger_error('array_column(): The index key should be either a string or an integer', E_USER_WARNING
);
71 $paramsInput = $params[0];
72 $paramsColumnKey = ($params[1] !== null) ?
(string) $params[1] : null;
74 $paramsIndexKey = null;
75 if (isset($params[2])) {
76 if (is_float($params[2]) ||
is_int($params[2])) {
77 $paramsIndexKey = (int) $params[2];
79 $paramsIndexKey = (string) $params[2];
83 $resultArray = array();
85 foreach ($paramsInput as $row) {
87 $keySet = $valueSet = false;
89 if ($paramsIndexKey !== null && array_key_exists($paramsIndexKey, $row)) {
91 $key = (string) $row[$paramsIndexKey];
94 if ($paramsColumnKey === null) {
97 } elseif (is_array($row) && array_key_exists($paramsColumnKey, $row)) {
99 $value = $row[$paramsColumnKey];
104 $resultArray[$key] = $value;
106 $resultArray[] = $value;