update page now

Voting

: four plus one?
(Example: nine)

The Note You're Voting On

ff2 AT hotmail DOT co DOT uk
7 years ago
Because the function was not available in my version of PHP, I wrote my own version and extended it a little based on my needs.

When you give an $indexkey value of -1 it preserves the associated array key values.

EXAMPLE:

$sample = array(
    'test1' => array(
        'val1' = 10,
        'val2' = 100
    ),
    'test2' => array(
        'val1' = 20,
        'val2' = 200
    ),
    'test3' => array(
        'val1' = 30,
        'val2' = 300
    )
);

print_r(array_column_ext($sample,'val1'));

OUTPUT:

Array
(
    [0] => 10
    [1] => 20
    [2] => 30
)

print_r(array_column_ext($sample,'val1',-1));

OUTPUT:

Array
(
    ['test1'] => 10
    ['test2'] => 20
    ['test3'] => 30
)

print_r(array_column_ext($sample,'val1','val2'));

OUTPUT:

Array
(
    [100] => 10
    [200] => 20
    [300] => 30
)

<?php
function array_column_ext($array, $columnkey, $indexkey = null) {
    $result = array();
    foreach ($array as $subarray => $value) {
        if (array_key_exists($columnkey,$value)) { $val = $array[$subarray][$columnkey]; }
        else if ($columnkey === null) { $val = $value; }
        else { continue; }
            
        if ($indexkey === null) { $result[] = $val; }
        elseif ($indexkey == -1 || array_key_exists($indexkey,$value)) {
            $result[($indexkey == -1)?$subarray:$array[$subarray][$indexkey]] = $val;
        }
    }
    return $result;
}
?>

<< Back to user notes page

To Top