Question :
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?
Answer :
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
)
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
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.