How to return the index of an array and its value in different variables?

3

I have an array of the following structure

Matriz[indice][valor]

How do I return the index in one variable, and the value in another?

Exdrúxulo example:

$indice = $matriz[indice]

And for the value:

$valor = $matriz[indice][valor]

Data examples:

codigo = 116500, valor 10
codigo = 194800, valor 7
codigo = 245300, valor 40
    
asked by anonymous 14.05.2015 / 02:56

1 answer

6

There are two functions called:

$array_keys = array_keys($array); // retorna só as chaves
$array_values = array_values($array); // retorna só os valores

Example:

$array = array('194800' => 'Forest', '194811' => 'River', '194812' => 'Sky');

$array_keys = array_keys($array);
$array_values = array_values($array);

print_r($array_keys);
print_r($array_values);

You can also add key + value:

$array = array_combine($keys, $values);

In the loop:

// para mostrar os valores. por padrão já vai retornar só os valores,
// mas você pode aplicar a função array_values($array) se quiser.
foreach ($array as $result) {
    echo $result; 
    echo "<br>";
} 
// para mostrar as chaves
foreach (array_keys($array) as $result) {
    echo $result; 
    echo "<br>";
} 

And to show key and value in the loop:

foreach ($array as $key => $value) {
    echo "Key: $key; Value: $value<br />\n";
}
    
14.05.2015 / 03:06