-2

I want to remove specific value of array. this's my code:

HTML

<form action="" method="post">
<input type="text" name="user">
<input type="submit" value="Watch">
</form>

PHP

$user='';

if ( isset ( $_POST['user'] ) ) { $user = $_POST['user']; }

$dir = "images/".$user.'/';

$dh = opendir ( $dir );

while ( false !== ($filename = readdir( $dh ) ) ) {
    $files[] = $filename; 
}

$files = array_diff ( $files, array('.','..') );

$e = count($files);

for ( $i=0; $i<$e; $i++ ) { echo $files[$i]; }

Output

user/.
user/..
user/HTML.txt
user/CSS.txt
user/JavaScript.txt

i tried array_diff() to remove '.' and '..'.

i get noticed offset 0 on for value by latest WAMP.

and how to make While version to For version loop that use opendir, and readdir?

lynx pravoka
  • 71
  • 1
  • 1
  • 9

3 Answers3

1

User If .. and condition no need to use array_diff

while ( false !== ($filename = readdir( $dh ) ) ) {
    if($filename != '.' && $filename != '..') {
        $files[] = $filename; 
    }
}
sandip patil
  • 638
  • 4
  • 8
1

TBI's answer is recommended, for your particular case; it makes sense to never put it in the array in the first place. However, to match the title of your question, to remove an element from an array, you should use unset:

foreach($files as $key => $file){
    if($file == '.' || $file =='..'){
        unset($key);
    }
}
Alex
  • 1,565
  • 2
  • 9
  • 13
0

You could use if() condition, like -

while ( false !== ($filename = readdir( $dh ) ) ) {
    if($filename != '.' || $filename != '..') {
        $files[] = $filename; 
    }
}

Now, you dont need to use array_diff

TBI
  • 2,789
  • 1
  • 17
  • 21