-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?

5
  • What is the desired output Commented Aug 19, 2014 at 5:55
  • possible duplicate of Removing array item by value Commented Aug 19, 2014 at 5:56
  • Utkarsh : i want to remove . and ... but i get notice offset 0 on For i variabel value Commented Aug 19, 2014 at 5:59
  • pc-shooter : thanks for the tag. but the answer on that is already in my code. i get error noticed offset 0. Commented Aug 19, 2014 at 6:02
  • possible duplicate of Delete an element from an array Commented Aug 19, 2014 at 6:02

3 Answers 3

1

User If .. and condition no need to use array_diff

while ( false !== ($filename = readdir( $dh ) ) ) {
    if($filename != '.' && $filename != '..') {
        $files[] = $filename; 
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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);
    }
}

Comments

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

1 Comment

TBI : theres wrong expression that in above codes. ||. it should be &&. thank you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.