How to display a certain position of an associative array?

Asked

Viewed 5,070 times

4

This is my array associative:

$vetor = array(
 "Nome"=> "posicao1",
 "Telefone"=> "posicao2",
 "Idade"=> "posicao3",
 "Sexo"=> "posicao4"
);

To display its contents I can use the foreach();

foreach($vetor as $campo => $valor){
    echo "Na posicao ".".$campo_echo." está o: ".$valor."<br>";
}

But, what if I want to display only the two values? And if I want to display only three values? How can I do this?

I tried to use the for, but without success:

for($i=0; $i<=1; $i++){
 echo $vetor[$i];
}
  • 1

    echo $vetor[3] .'-'. $vetor[2]; that? in the second example $i should start at 1

  • your Count will be dependent on how many values you want to set, starting or ending at your set value in $i

  • 1

    When you say "display only the two values" you know the keys to these two values?

  • These two examples you gave me work only when I put numbers in the keys, 1, 2etc. Modifiquei o código para exemplificar o que quero fazer. Digamos que eu queira exibir somente os três primeiros campos: os valores dename, telephone e ìdade. Would use the for, correct?

  • This example echo $vector[0] . '-'. $vector[1] .....;funciona. Porém, se meu array tiver 100, 200, 300 elementos, fazer isso de um a um não é uma boa prática, logo tenho que automatizar isso. Daí, entra ofor`. How can I do this?

  • My suggestion was based on the information of the question, in the first version were indices numbers are now associative and also was not commented on 100 or 300 indices/keys, I could not understand right q vc want, the second comment seems to be the solution.

  • I left with numbers to exemplify, did not know that leaving keys with numbers the same are considered as indexes. As I said, if my array has 300 keys/elements and you only want to display the first 250, how can I do that? This is my question. The difference is that the example I did is much smaller, I want to display the Indice 0 and 1, that is, the first two. I’m sorry if I expressed myself badly.

  • The question from the beginning was a array associative. They were strings. Even if they were numerical, it could still be a array associative. The keys of this type of array may be of any kind.

  • $vetor = array(&#xA; "Nome"=> "posicao1",&#xA; "Telefone"=> "posicao2",&#xA; "Idade"=> "posicao3",&#xA; "Sexo"=> "posicao4"&#xA;); How do I display only the first two fields with one for?

  • for($i=1; $i<=3; $i++){ echo $vetor[$i]."<br>"; }. Or, in the first $i knitting the 1 for 0 and the 3 for 2, also doesn’t work :/

  • @Luizsantos Did the answer solve your problem? Do you think you can accept it? If you don’t know how you do it, see [tour]. This would help a lot to indicate that the solution was useful to you and to give an indication that there was a satisfactory solution. You can also vote on any question or answer you find useful on the entire site.

Show 6 more comments

2 answers

5

  • With the foreach I display ALL elements of mine array. Let’s say I only want to display the first two menus of array or just the first three. How can I do this within a for or some loop structure?

1

This repeat loop iterates the integer array and displays the associative key and its value.

foreach ($vetor as $k => $v) {
    echo $k.' -> '.$v.PHP_EOL.'<br>';
}

If you wanted to display a certain range, you can only create conditional within the repeat loop.

Example, if you want to display only the second and the third

$c = 1;
foreach ($vetor as $k => $v) {
    if ($c == 2 || $c == 3) {
        echo $k.' -> '.$v.PHP_EOL.'<br>';
    }
    $c++;
}

But depending on the case may not be very good as it would still be iterating the entire array.

It could do otherwise to save memory and processing resources. Even if it is a small saving. The most interesting thing is that it makes the routine more dynamic, that is, reusable:

$arr = array(
    'Nome'=> 'posicao1',
    'Telefone'=> 'posicao2',
    'Idade'=> 'posicao3',
    'Sexo'=> 'posicao4'
);


function foo($arr, $ini, $end) {
    // O terceiro parâmetro como true, preserva os índices.
    return array_slice($arr, $ini-1, $end-1, true);
}

// Isso aqui retorna o array "cortado" definindo parâmetros de forma mais simplificada.
$arr = foo($arr, 2, 3);

// Itera tudo normalmente sem precisar fazer firula.
// O laço de repetição fica "livre" de condicionais.
foreach ($arr as $k => $v) {
    echo $k.' -> '.$v.PHP_EOL.'<br>';
}

/*
[retorno]
Telefone -> posicao2 
Idade -> posicao3
*/

I emphasize that each solution depends on the situation. In a larger array, for example, more than 20 items, I believe better Slice. In a smaller array, do as in the first example with conditional inside the repeat loop.

Browser other questions tagged

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