How to catch the key in a while loop?

Asked

Viewed 502 times

3

Let’s say I have an associative array

$array=array(
     "teste" => "1".
     "teste2" => "2"
);

foreach($array AS $key=>$arr){
    echo $key;
} 

how does loop? has some way?

  • Well, that’s not a multidimensional array, it’s an array of 2 associative indices.

  • 1

    Yes is possible also with the function key()!

  • foreach is loop. I think I better ask how it does with "while", if the doubt is this (in the title already has, I say in the body of the question).

1 answer

2


You can do it in two ways. Given the array:

$array = array(
    'teste' => '1',
    'teste2' => '2'
);

1. Using the method Current(), which returns the current element of the array, along with the methods key() to take the key of the current element, and next() to advance the array’s internal pointer (so that current() take the next element in the next iteration):

while ($value = current($array)) {
    echo key($array) . "\n";
    next($array);
}

2. Using the method each(), which does the same as the 3 methods above together: returns the key pair/current value of the array, and advances the pointer. Example:

while (list($key, $value) = each($array)) {
    echo $key . "\n";
}

See the code running on Ideone.

Browser other questions tagged

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