How do I get the index number of an array?

0

I have the following array:

Array
(
    [CPF_CNPJ] => Array
    (
    )
    [TIPO] => Array
    (
    )
    [NOME] => Array
    (
    )
)

I know that key(array) returns the NAME of the current key in a loop, but would like to get the index of the key and not the name.

Example

[CPF_CNPJ] = 0
[TIPO] = 1
[NOME] = 2

Will I have to foreach do this?

I did not see the PHP manual as a function for this.

    
asked by anonymous 03.08.2016 / 15:47

1 answer

4

For this, if I understood correctly, you can use array_keys () :

$arr = array(
   'CPF_CNPJ' => array(),
   'TIPO' => array(),
   'Nome' => array(),
);

$arr = array_keys($arr);

Output from $arr :

Array
(
    [0] => CPF_CNPJ
    [1] => TIPO
    [2] => Nome
)

To know the key of a given value (original array key) of this new array :

array_search('TIPO', $arr); // 1

In short, for example, to know the numerical index of the key 'Nome' :

echo array_search("Nome", array_keys($arr)); // chave 2
    
03.08.2016 / 15:49