Forum Moderators: coopster
<?php
$dirarray[] = '0 test';
$dirarray[] = '1 test';
$dirarray['css'] = 'css test';
$dirarray['Templates'] = 'Templates test';
echo '<pre>'; print_r($dirarray);
unset($dirarray['css'], $dirarray['Templates']);
unset($dirarray[0], $dirarray[1]);
print_r($dirarray); echo '</pre>';
?>
Does the second array still contain the string index array elements?
I've got a bit confused now, and perhaps I'm not going about things the right way...
Basically I've got an array from reading a list of all the directories in a location:
Array ( [0] => . [1] => .. [2] => css [3] => includes [4] => information for staff [5] => Templates [6] => information for students )
foreach($dirarray as $diritem){
//if this == "Css" delete it from the array
//if this == "Templates" delete it from the array
}
//remove any items we don't want from our array
$deletekey = array_search('css', $dirarray);
unset($dirarray[$deletekey]);
$deletekey = array_search('Templates', $dirarray);
unset($dirarray[$deletekey]);
$deletekey = array_search('.', $dirarray);
unset($dirarray[$deletekey]);
$deletekey = array_search('..', $dirarray);
unset($dirarray[$deletekey]);
// fails, $diritem isn't a reference to the original array
foreach($dirarray as $diritem){
if($diritem == "css") unset($diritem);
}
$diritem is really just a copy of the value of the current array element... this foreach construct doesn't even give you a way of knowing what the original index was. However, there's a different way of writing foreach that gives you more power.
// works, $index gives us a way to go back and modify the original array
foreach($dirarray as $index=>$diritem){
if($diritem == "css") unset($dirarray[$index]);
}
You can use whatever variable names for $index and $diritem you'd like, many use
$k=>$vor
$key=>$value.
So back to the problem at hand. :) You have a known list of invalid directories, so put those in an array then loop through the dynamic list of directories and check each one against the invalid list. in_array [php.net] is a handy way to do this.
$dirarray = array( '.', '..', 'css', 'includes', 'information for staff', 'Templates', 'information for students');
$removearray = array( '.', '..', 'css', 'Templates');
foreach($dirarray as $k=>$v){
if(in_array($v, $removearray)){
unset($dirarray[$k]);
}
}
echo '<pre>'; print_r($dirarray); echo '</pre>';