Doubt - Array php return

Asked

Viewed 144 times

0

I’m a beginner in php, and I came across the next problem. I have a function that returns me an array that comes from the database.

$teste = dados($conexao);

And I do:

print_r($teste);

It returns me the following data:

Array (
    [0] => Array (
        [nome] => Maria
        [idade] => 26
    ) 
    [1] => Array (
        [nome] => Joao
        [idade] => 18
    )
)

Now comes the problem, I want to add one of the information in several different, ex:

$nomeJoao = $teste[1].nome;
print_r($nomeJoao);

I get the following error on the screen:

Warning: Use of Undefined Constant name - assumed 'name' (this will throw an Error in a Future version of PHP)

Notice: Array to string Conversion

  • $nomeJoao = $teste[1]['nome']; Resolves ?

3 answers

1

In the PHP the "." point is used for concatenation and not for referencing attributes of an array. To reference an associative array property you need to pass the property name.

$teste = [['nome'=>'João', 'idade'=>20], ['nome'=>'Maria', 'idade'=>25]];
print_r( $teste[0]['nome']); // Aqui eu pego o nome do primeiro array
  • 1

    Obg, you helped me a lot!

0

In php, if you want to reference a position of a array nominal, should do as follows (considering its example):

Array (
    [0] => Array (
        [nome] => Maria
        [idade] => 26
    ) 
    [1] => Array (
        [nome] => Joao
        [idade] => 18
    )
)

var_dump($teste[1]['nome']);

Joao

0

In a given item

$teste[0]['indice'] = 'valor';

foreach to save on all

foreach ($teste as $key => $value){
 $value['indice'] = 'valor';
}

more questions for foreach php foreach php.net

  • Thanks!! Helped me a lot!

  • mark as accepted and vote ^^

Browser other questions tagged

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