Jump to content

in_array not working--trouble with needle array


RopeADope

Recommended Posts

Hi all.

 

I've got this bit of code:

   $needles=array(`.`,`..`,`css`,`php`,`input_forms`);

   $t1=scandir($_SERVER['DOCUMENT_ROOT']);
   foreach($t1 as $t1_value){
      if(!is_dir($t1_value)){
         unset($t1[array_search($t1_value,$t1)]);
      }else{
         unset($t1[array_search($needles,$t1)]);
      }
   }

 

As you can see, I'm trying (in the else statement) to array search $t1 for everything in $needles, then unset the matches from $t1.  But its not working and I'm not sure why.  I also tried...

unset($t1[array_search(in_array($needles,$t1),$t1)]);

 

But that doesn't work either.  It only removes the "." directory from the array.  Any ideas on what's going wrong?

Link to comment
Share on other sites

The problem is that you are using an array as your needle in the array_search() in your else statement.  It is using only the value at key 0 for this (a.k.a your '.' directory).

 

Here's a quick fix:

 

<?php

$needles=array('.','..','css','php','input_forms');
$t1=scandir($_SERVER['DOCUMENT_ROOT']);

foreach($t1 as $t1_value){
   if (!is_dir($t1_value)){
      unset($t1[array_search($t1_value,$t1)]);
   }else if (array_search($t1_value,$needles) !== false){
      unset($t1[array_search($t1_value,$t1)]);
   }
}
   
?>

 

This time, if it's a directory, it is checked against the $needles array, and if it does in fact match, then it is unset from the scandir array.

 

-nethnet

Link to comment
Share on other sites

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.