Display associative array elements with foreach
Hello, guys. I would like to display the elements of an associative array as follows:
Nome: José
Idade: 32
Profissão: Médico
Nome: Rafaela
Idade: 28
Profissão: Dentista
All on the same page. And the code I'm using is as follows:
<?php
$usuarios = array(
array("nome"=>"José", "idade"=>32, "profissao"=>"Médico"),
array("nome"=>"Rafaela", "idade"=>28, "profissao"=>"Dentista"),
array("nome"=>"Gabriela", "idade"=>18, "profissao"=>"Não tem")
);
foreach ($usuarios as $informacoes => $dados){
echo $informacoes . " : ";
echo $dados;
}
?>
But with this code I get the following error:
0 :
Notice: Array to string conversion in /opt/lampp/htdocs/Development/PHP/Exercicio9/usuarios.php on line 10
Array1 :
Notice: Array to string conversion in /opt/lampp/htdocs/Development/PHP/Exercicio9/usuarios.php on line 10
Array2 :
Notice: Array to string conversion in /opt/lampp/htdocs/Development/PHP/Exercicio9/usuarios.php on line 10
Array
Searching, I realized that to show the array it would be necessary to give a print_r
instead of the echo
, but this command literally shows the array.
I would like to know if it is possible and how can I do to display the indexes and their values of the array as I showed.
Right now, thank you.
1
Author: boomboxarcade, 2017-03-05
2 answers
You can loop inside the other:
$usuarios = array(
array("nome"=>"José", "idade"=>32, "profissao"=>"Médico"),
array("nome"=>"Rafaela", "idade"=>28, "profissao"=>"Dentista"),
array("nome"=>"Gabriela", "idade"=>18, "profissao"=>"Não tem")
);
foreach($usuarios as $informacoes) {
foreach($informacoes as $chave => $valor) {
echo $chave;
echo ': ';
echo $valor;
echo '<br />';
}
}
2
Author: jlHertel, 2017-03-05 20:07:56
You put an associative array inside another assossiative array, try using this Code:
<?php
header('Content-type: text/html; charset=utf-8');
$usuarios = array(
array("nome"=>"José", "idade"=>32, "profissao"=>"Médico"),
array("nome"=>"Rafaela", "idade"=>28, "profissao"=>"Dentista"),
array("nome"=>"Gabriela", "idade"=>18, "profissao"=>"Não tem")
);
foreach ($usuarios as $usuario){
echo "Nome : " . $usuario['nome'] . "<br>";
echo "Idade :" . $usuario['idade'] . "<br>";
echo "Profissao :" . $usuario['profissao'] . "<br>";
echo "<br>";
}
?>
1
Author: Eric Castro, 2017-03-05 18:23:13