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?

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.