Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate to array_column()

Tags:

arrays

php

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.

like image 321
Sizzling Code Avatar asked Dec 11 '14 12:12

Sizzling Code


1 Answers

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:

like image 66
Pupil Avatar answered Oct 05 '22 18:10

Pupil