Last Updated: February 25, 2016
·
3.461K
· message

array_column implementation for PHP <= 5.5


function array_column(array $input, $columnKey, $indexKey = null)
{
    $array = array();
    foreach ($input as $value) {
        if ( ! isset($value[$columnKey])) {
            trigger_error("Key \"$columnKey\" does not exist in array");
            return false;
        }

        if (is_null($indexKey)) {
            $array[] = $value[$columnKey];
        } else {
            if ( ! isset($value[$indexKey])) {
                trigger_error("Key \"$indexKey\" does not exist in array");
                return false;
            }
            if ( ! is_scalar($value[$indexKey])) {
                trigger_error("Key \"$indexKey\" does not contain scalar value");
                return false;
            }
            $array[$value[$indexKey]] = $value[$columnKey];
        }
    }

    return $array;
}

1 Response
Add your response

This implementation is wrong according to the PHP documentation http://php.net/manual/en/function.array-column.php.

If the second parameter is NULL, it should return the complete array.

Maybe you could look at ramsey's implementation in https://github.com/ramsey/array_column

over 1 year ago ·