How to know the names of array positions in php?

3

I submit the javascript 2 arrays with the following data:

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

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

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

It happens that I have 2 different buttons for the form, where each one generates this array. Can I know the name of the array positions?

    
asked by anonymous 18.09.2017 / 20:04

3 answers

5

To get the key names of an array 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);

Output:

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

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

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

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

Output:

Array
(
    [2] => modulo
    [6] => categoria
    [3] => outra
)
    
18.09.2017 / 20:10
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 find out more about the php.net page

    
18.09.2017 / 20:14
2

If you already scroll through the array , you can get the key directly with foreach :

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

See working at Ideone .

Obviously this is only effective if you need to go through the array . If you only want to get the list of keys, use array_keys , as indicated in the other answers.

    
18.09.2017 / 20:21