How to know the names of the array positions in php?

Asked

Viewed 322 times

3

I send javascript 2 arrays with the following data:

values = {'tipoLicenciamento':tipoLicenciamento,'modulo':modulo} ;
values = {"modulo":modulo,"categoria":6};

In my php I get something like when I give a printr()

Array ( [modulo] => 2 [categoria] = 6)
Array ( [tipoLicenciamento] => 1 [modulo] => 2 ) 

I happen to have 2 different buttons for the form, where each one generates this array. I can know the names of the positions of the array?

  • Want only the array key names?

  • 1

    "Name of positions" would be the keys of the array? I mean, in a result modulo, categoria and the other tipoLicenciamento, modulo? Would that be?

  • exactly that Anderson

3 answers

5


To take the name of an array’s keys one way is to use the function array_keys()

$arr = array('modulo' => 2, 'categoria' => 6, 'tipoLicenciamento' => 3);
$chaves = array_keys($arr);

echo "<pre>";
print_r($chaves);

Exit:

Array
(
    [0] => modulo
    [1] => categoria
    [2] => tipoLicenciamento
)

Another way when appropriate is to invert the values by the keys, array_fliper() does it. It’s important comment that if there are two or more equal values who will prevail is the last key in the case outra.

$arr = array('modulo' => 2, 'categoria' => 6, 'tipoLicenciamento' => 3, 'outra' => 3);
$chaves = array_flip($arr);

echo "<pre>";
print_r($chaves);

Exit:

Array
(
    [2] => modulo
    [6] => categoria
    [3] => outra
)
  • Got it, I was using the Keys array erroneously, thank you

3

The function you are looking for (if I understand correctly), is called array_keys().

To use:

<?php

     $keys = array_keys($_POST['nome']);//Armazena nome das posições como um array
     print_r($keys);//Saída: Array ([0] => key [1] => other)

You can see more about her page in php.net

2

If you ever walk the array, you can get the key directly with the foreach:

foreach($_POST as $key => $value) {
    echo $key;
}

See working on Ideone.

Obviously this way is only efficient if you need to go through the array. If you only want to get the key list, use array_keys, as indicated in the other replies.

Browser other questions tagged

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