How to display certain position of an associative array?

1

This is my associative array :

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

To display the contents of it, I can use 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 does your self want to display only three values? How can I do this?

I tried to use for , but to no avail:

for($i=0; $i<=1; $i++){
 echo $vetor[$i];
}
    
asked by anonymous 12.05.2016 / 16:27

2 answers

4

You do this with the array_keys() function.

foreach (array_keys($vetor) as $index => $key) {
    echo $index . ": " . $key . " => " . $vetor[$key] . "\n";
}

$array = array_keys($vetor);
for ($i = 0; $i <= 1; $i++) {
    echo $array[$i] . " => " . $vetor[$array[$i]] . "\n";
}

See working on ideone or PHP Sandbox .

    
12.05.2016 / 16:38
0

This loop repetition iterates through the entire 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 particular range, you can only create conditionals within the loop.

Example, if you want to display only the second and 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's a small economy. What is most interesting 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 stress that each solution depends on the situation. In a larger array, for example, more than 20 items, I believe the slice better. In a smaller array, do as in the first example with conditional inside the loop repeat.

    
03.10.2016 / 20:09