3 * This file was recommended at http://php.net/manual/en/function.array-column.php#refsect1-function.array-column-seealso
5 * This file is part of the array_column library
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
10 * @copyright Copyright (c) Ben Ramsey (http://benramsey.com)
11 * @license http://opensource.org/licenses/MIT MIT
14 if (!function_exists('array_column')) {
16 * Returns the values from a single column of the input array, identified by
19 * Optionally, you may provide an $indexKey to index the values in the returned
20 * array by the values from the $indexKey column in the input array.
22 * @param array $input A multi-dimensional array (record set) from which to pull
24 * @param mixed $columnKey The column of values to return. This value may be the
25 * integer key of the column you wish to retrieve, or it
26 * may be the string key name for an associative array.
27 * @param mixed $indexKey (Optional.) The column to use as the index/keys for
28 * the returned array. This value may be the integer key
29 * of the column, or it may be the string key name.
32 function array_column($input = null, $columnKey = null, $indexKey = null)
34 // Using func_get_args() in order to check for proper number of
35 // parameters and trigger errors exactly as the built-in array_column()
37 $argc = func_num_args();
38 $params = func_get_args();
41 trigger_error("array_column() expects at least 2 parameters, {$argc} given", E_USER_WARNING);
45 if (!is_array($params[0])) {
47 'array_column() expects parameter 1 to be array, ' . gettype($params[0]) . ' given',
53 if (!is_int($params[1])
54 && !is_float($params[1])
55 && !is_string($params[1])
56 && $params[1] !== null
57 && !(is_object($params[1]) && method_exists($params[1], '__toString'))
59 trigger_error('array_column(): The column key should be either a string or an integer', E_USER_WARNING);
64 && !is_int($params[2])
65 && !is_float($params[2])
66 && !is_string($params[2])
67 && !(is_object($params[2]) && method_exists($params[2], '__toString'))
69 trigger_error('array_column(): The index key should be either a string or an integer', E_USER_WARNING);
73 $paramsInput = $params[0];
74 $paramsColumnKey = ($params[1] !== null) ? (string) $params[1] : null;
76 $paramsIndexKey = null;
77 if (isset($params[2])) {
78 if (is_float($params[2]) || is_int($params[2])) {
79 $paramsIndexKey = (int) $params[2];
81 $paramsIndexKey = (string) $params[2];
85 $resultArray = array();
87 foreach ($paramsInput as $row) {
89 $keySet = $valueSet = false;
91 if ($paramsIndexKey !== null && array_key_exists($paramsIndexKey, $row)) {
93 $key = (string) $row[$paramsIndexKey];
96 if ($paramsColumnKey === null) {
99 } elseif (is_array($row) && array_key_exists($paramsColumnKey, $row)) {
101 $value = $row[$paramsColumnKey];
106 $resultArray[$key] = $value;
108 $resultArray[] = $value;