How to get the index number of an array?

Asked

Viewed 4,482 times

0

I have the following array:

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

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

Example

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

I’ll have to make one foreach for that reason?

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

1 answer

5


For that, if I understand 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

Summarizing, e.g.: to know the numerical index of the key 'Nome':

echo array_search("Nome", array_keys($arr)); // chave 2
  • um, I came to see this function, actually it numbers the indices, but actually I wanted to take the number Indice without having to extend the routine too much, it would be like this: $Indice = $meuarray["CPF_CNPJ"]. Itemindex, in Delphi for example we can do Number = Minhalista("field"). Itemindex;

  • 1

    @Marcelo, I understand exactly, but that I know and from what I have seen now that you told me this: https://www.google.pt/search?client=ubuntu&channel=fs&q=get+numeric+index+of+ass+array&ie=utf-8&oe=utf-8&gfe_rd=cr&ei=OfihV-_jFuas8weX3JOQDg#Channel=fs&q=get+Numeric+index+of+assciative+array+php, seems to make all use of these functions, I believe that in php the best way is so and there is no back to give

  • 1

    @Marcelo Just do it like this: $indice = array_search('CPF_CNPJ', array_keys($meuArray));

  • 1

    Exact as @zekk said and as it is at the end of the answer is also just a line

  • That’s really it, inattention on my part.

  • It’s okay @Marcelo. I’m glad you decided

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.