31

I have used array_column() in a project, and after uploading I found out that only PHP 5.5 or above support this function, and I think the hosting I use don't support PHP 5.5 or above.

So I want to know if is there any alternate to fix this error?

This is how I am using array_count in my project:

array_count_values(array_column(json_decode(json_encode($queryResultArray), true), $idForBar));

This is working fine in my local xampp and wampp also, but on server it is giving issue. Looking any alternate function or solution.

Pupil
  • 23,834
  • 6
  • 44
  • 66
Sizzling Code
  • 5,932
  • 18
  • 81
  • 138
  • 3
    wtf are you sure about `json_decode(json_encode(` ? Like, why?? – MightyPork Dec 11 '14 at 12:16
  • 7
    Well you know what my solution would be: Upgrade PHP to 5.5, or move to a host that actually supports development and moving forward! – Niet the Dark Absol Dec 11 '14 at 12:16
  • 1
    well, just break it into parts and just do it without it. its not complicated. – Kevin Dec 11 '14 at 12:19
  • 2
    if you want a library solution https://github.com/ramsey/array_column – Kevin Dec 11 '14 at 12:20
  • @MightyPork i used json_decode(json_encode cuz i wanted to convert object array to associated array. i know its not a good way but it gets the job done. but i didnt opened the question for json question. – Sizzling Code Dec 11 '14 at 12:22
  • @MightyPork `json_decode(json_encode(` is OK, because there is `json_decode(json_encode(...., true));` do you see? check the documentation... – Legionar Dec 11 '14 at 12:22
  • @Legionar not saying it doesn't work, but it looks like a very inefficient and hacky solution – MightyPork Dec 11 '14 at 12:23
  • 1
    @MightyPork - hacky, arguable, but actually very efficient – Mark Baker Dec 11 '14 at 12:25
  • Your variable is named `$queryResultArray`... - may I ask, are you trying to apply this function to the result set of an SQL query? – silkfire Dec 11 '14 at 12:51
  • @silkfire no, that is just the name query. its not actuall query, it includes the result fethed from db.. :) – Sizzling Code Dec 11 '14 at 12:53
  • @SizzlingCode If it's the result fetched from your DB, in `PDO` you can use a special fetch mode which will solve this entire problem for you. How does your query look like? – silkfire Dec 11 '14 at 12:56

6 Answers6

85

Add your own function array_column if you PHP version does not support it:

<?php
if (! function_exists('array_column')) {
    function array_column(array $input, $columnKey, $indexKey = null) {
        $array = array();
        foreach ($input as $value) {
            if ( !array_key_exists($columnKey, $value)) {
                trigger_error("Key \"$columnKey\" does not exist in array");
                return false;
            }
            if (is_null($indexKey)) {
                $array[] = $value[$columnKey];
            }
            else {
                if ( !array_key_exists($indexKey, $value)) {
                    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;
    }
}

Reference:

Nikita
  • 4,576
  • 1
  • 14
  • 11
Pupil
  • 23,834
  • 6
  • 44
  • 66
  • 8
    Whats the difference between your implementation and Ben Ramsey's https://github.com/ramsey/array_column/blob/master/src/array_column.php – NBPalomino Aug 08 '15 at 00:54
  • 1
    Better to put the function array_column() in an include file and use require at the top of your code. This way it only gets included if the function does not exist. Otherwise php will complain about redefinition at parse time if the function already exists. – user603749 Sep 22 '17 at 12:36
  • @user603749, there is alrady check if function does not exist, then our code. :) – Pupil Sep 25 '17 at 06:03
  • Additionally, you can just use `array_column()` with objects if you're using `PHP7+`. You can visit this link: http://php.net/manual/en/function.array-column.php#refsect1-function.array-column-changelog – Blues Clues Apr 24 '18 at 07:55
  • This function did not work if returning values are array's. Used @doub1ejack suggested solution and it worked perfectly. His suggestion was to use the actual code form the PHP 5.5+ library [here](https://github.com/ramsey/array_column/blob/master/src/array_column.php) – Jeff Aug 03 '18 at 02:53
  • 2
    If support of objects needed, this can be used: https://www.php.net/manual/en/function.array-column.php#119754 – degers Jul 17 '19 at 08:04
24

You can also use array_map() function if you haven't array_column() because of PHP<5.5:

Example:

$a = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    )
);

array_column($a, 'last_name');

Becomes:

array_map(function($element) {
  return $element['last_name'];
}, $a);

So it your case the code will be:

array_count_values(
  array_map(function($arr) use ($idForBar) {
    return $arr[$idForBar];
  }, $queryResultArray)
);

This above is working on PHP 5.3.0 and above!

If you have < PHP 5.3.0, as you wrote PHP 5.2.17, just use simple function:

function get_field_data($array, $field, $idField = null) {
    $_out = array();

    if (is_array($array)) {
        if ($idField == null) {
            foreach ($array as $value) {
                $_out[] = $value[$field];
            }
        }
        else {
            foreach ($array as $value) {
                $_out[$value[$idField]] = $value[$field];
            }
        }
        return $_out;
    }
    else {
        return false;
    }           
}

And the usage:

$output = get_field_data($queryResultArray, $idForBar);
Legionar
  • 7,472
  • 2
  • 41
  • 70
10

You can also use the alternative code of array_column(), it's simple just paste below line and replace your variable.

Code:

array_map(function($element){return $element['last_name'];}, $a);
halfer
  • 19,824
  • 17
  • 99
  • 186
Codebrekers
  • 754
  • 1
  • 11
  • 29
4

Using array_map() instead, something like:

array_count_values(
    array_map(
        function($value) use ($idForBar) {
            return $value[$idForBar];
        },
        json_decode(
            json_encode($queryResultArray),
            true
        )
    )
);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • im really really greatful to your reply but i got stucked in other problem after using your code. `syntax error, unexpected T_FUNCTION, expecting ')'` To which i searched google and i found out anonymous functions supported after 5.3.0?? `http://stackoverflow.com/questions/3723748/php-version-5-2-14-parse-error-syntax-error-unexpected-t-function-expecting` How to tackle this?? – Sizzling Code Dec 11 '14 at 12:43
  • What version of PHP are you actually running? If you get that error, it suggests a very old, unsupported version (PHP < 5.3) that doesn't support closures; in which case, read Niet's comment on your question – Mark Baker Dec 11 '14 at 12:45
  • I just checked with `phpinfo();` server php version is `PHP Version 5.2.17` :( – Sizzling Code Dec 11 '14 at 12:51
  • Sir Any solution possible for 5.2.17? – Sizzling Code Dec 11 '14 at 12:58
  • @SizzlingCode If you have < PHP 5.3.0, as you wrote PHP 5.2.17, just use simple function, as I updated my answer... – Legionar Dec 11 '14 at 14:11
4

You can always use another implementation of function array_column

if (!function_exists('array_column')) {
    function array_column(array $array, $columnKey, $indexKey = null)
    {
        $result = array();
        foreach ($array as $subArray) {
            if (!is_array($subArray)) {
                continue;
            } elseif (is_null($indexKey) && array_key_exists($columnKey, $subArray)) {
                $result[] = $subArray[$columnKey];
            } elseif (array_key_exists($indexKey, $subArray)) {
                if (is_null($columnKey)) {
                    $result[$subArray[$indexKey]] = $subArray;
                } elseif (array_key_exists($columnKey, $subArray)) {
                    $result[$subArray[$indexKey]] = $subArray[$columnKey];
                }
            }
        }
        return $result;
    }
}
Wajeel
  • 41
  • 1
2

There is an official recommendation for PHP versions that don't support array_colum() under the "see also" section:

» Recommended userland implementation for PHP lower than 5.5

Their recommendation is another if (!function_exists('array_column')) approach, but the code is actually extracted from the array_column library and is a little more generalized than the examples on this page.

doub1ejack
  • 10,627
  • 20
  • 66
  • 125