Can't seem to work out why the return is not correct. It should be dir_3
, if echo
it's correct.
The function checks the existing_dirs
array, if $new_dir
exists, if it does if appends _xx
to $new_dir
if not it should return the $new_dir
. But it does not, however if you echo $new_dir
it's correct dir_3
.
Spent hours debugging, whats seems like a simple problem!
Thanks
function dir_name($new_dir, $count){
$existing_dirs = array('dir', 'dir_1', 'dir_2');
if(in_array($new_dir, $existing_dirs)){
$count ++;
if($count == 1) {
$new_dir = $new_dir . '_' . $count;
}
if($count > 1){
$dir_parts = explode('_', $new_dir);
$new_dir = $dir_parts[0] . '_' . $count;
}
dir_name($new_dir, $count);
} else {
//echo $new_dir;
return $new_dir;
}
}
echo dir_name('dir');
Seems you need return sth in if
case.
function dir_name($new_dir, $count){
$existing_dirs = array('dir', 'dir_1', 'dir_2');
if(in_array($new_dir, $existing_dirs)){
$count ++;
if($count == 1) {
$new_dir = $new_dir . '_' . $count;
}
if($count > 1){
$dir_parts = explode('_', $new_dir);
$new_dir = $dir_parts[0] . '_' . $count;
}
return dir_name($new_dir, $count);
} else {
//echo $new_dir;
return $new_dir;
}
}