How to return the index of a matrix and its value in different variables?

Asked

Viewed 1,272 times

3

I have a matrix of the following structure

Matriz[indice][valor]

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

Odd 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

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 join 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";
}
  • Ok, and how do I use it in the loop? type $code = array_keys($array) and for the value $value = array_values($array);

  • 1

    @Adrianoecris, I gave an update on the reply.

  • 3

    @Adrianoecris, http://php.net/manual/en/control-structures.foreach.php

  • The link above has several cool examples, take a look :)

Browser other questions tagged

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