how to get the key in a while loop?

3

Let's say I have an associative array

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

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

How do you loop? Do you have any way?

    
asked by anonymous 04.03.2016 / 22:40

1 answer

2

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

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

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

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

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

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

See the code running on Ideone .

    
04.03.2016 / 23:53