Using the do-while loop in an associative array in php

advertisements

I'm little confused as in how can I use do-while loop in an associative array in php. I don't have ordered indexes starting from 0 so I can't iterate simple as in case of C or Java

NOTE :: I specifically want do-while sort of behavior...i.e. loop s'd execute atleast once in the beginning


You can use the array_keys function.

$keys = array_keys($assocArray);
if(!empty($keys)) do{
  $key = array_pop($keys);
  // ...
}while(!empty($keys));

If you really want to use a do-while loop. But if a simple while loop is good for you, the first if isn't neccessary:

$keys = array_keys($assocArray);
while(!empty($keys)){
  $key = array_pop($keys);
  // ...
};

edit:

If you really want your loop to run at least once:

$keys = array_keys($assocArray);
do{
  $key = array_pop($keys);
  if($key===NULL){
    // first (and last) run for an empty array
  }else{
    // ...
  }
}while(!empty($keys));