Arjit
Arjit

Reputation: 147

How to get all keys out of associative array in php

I have an associative array in php. When I am doing a die on it, then I am getting proper values as follows:

array(1) { [0]=> array(1) { [123]=> string(5) "Hello" }}

But when I am trying extract out keys of this array into an new array, then I am not able to get keys out:

$uniqueIds = array_keys($myAssociativeArray);
die(var_dump($uniqueIds));
int(0) array(1) { [0]=> int(0) } 

Can any one tell me what I am doing wrong here? I want to get all the keys out of my associative array. And for this, I am referring to thread: php: how to get associative array key from numeric index?

Upvotes: 4

Views: 15646

Answers (3)

user353877
user353877

Reputation: 1221

The following recursively gets all the keys in an associative array

function getArrayKeysFlat($array) {
    if(!isset($keys) || !is_array($keys)) {
        $keys = array();
    }
    foreach($array as $key => $value) {
        $keys[] = $key;
        if(is_array($value)) {
            $keys = array_merge($keys,getArrayKeysFlat($value));
        }
    }
    return $keys;
}

Upvotes: 0

Your Common Sense
Your Common Sense

Reputation: 157838

$uniqueIds = array_keys($myAssociativeArray[0]);

Upvotes: 11

MIIB
MIIB

Reputation: 1849

    <?php
    function multiarray_keys($ar) {

        foreach($ar as $k => $v) {
            $keys[] = $k;
            if (is_array($ar[$k]))
                $keys = array_merge($keys, multiarray_keys($ar[$k]));
        }
        return $keys;
    }
$result = multiarray_keys($myAssociativeArray);
var_dump($result);
    ?> 

Upvotes: 1

Related Questions