Jump to content

Recommended Posts

Hi,

 

I have a script that read information from a directory (using scandir()), and puts it in an array.

 

Now I want to filter out all files and unvalid directories (ie: '.' and '..'), so that I keep the normal/visible directories.

 

Than I loop through the array with a while(isset($array[$i])).

 

When I use array_filter() to filter out the unwanted files/directories from the array, it will also delete the keys. So the keys arent for instance: 0, 1, 2, 3, 4, 5  but: 2, 3, 5

 

When I loop through the array it will say: key 0 (in the beginning, when $i = 0) is not set and so it will stop.

 

How can I re-generate the keys so there wont be gaps between the numbers?

 

Thanks,

 

Full-Demon

Link to comment
https://forums.phpfreaks.com/topic/54977-array-re-generate-the-key-list/
Share on other sites

You can use a foreach loop instead of a for loop to cycle through the array, so instead of

<?php
for($i=0;$i<count($array);i++)
{
$element = $array[$i];
// do the work
}
?>

do

<?php
foreach($array as $element)
{
// do the work
}
?>

 

If you really need to resequence the array, you can write a function to do that:

<?php
$bad_array = array(1=>'xyz',10=>'abc');
function resequence($ary) {
  $tmp = array();
  foreach ($ary as $ele)
      $tmp[] = $ele;
  return ($tmp);
}
$array = resequence($bad_array);
echo '<pre>' . print_r($array,true) . '</pre>';
?>

 

Ken

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.