directory - dirname() X amount of times on path of file PHP
Get the solution ↓↓↓I need to do adirname()
on a file path multiple times to exclude sub-folders, so like this:
dirname(dirname(dirname(__FILE__)));
The amount of times I need to do this on a file path is completely dynamic (not fixed) so I need to somehow do it variable$x
amount of times...
I could do this:
$x=6;//amount of sub-folders involved in the path
if($x==1){dirname(__FILE__);}
elseif($x==2){dirname(dirname(__FILE__));}
elseif($x==3){dirname(dirname(dirname(__FILE__)));}
elseif($x==4){dirname(dirname(dirname(dirname(__FILE__))));}//and so on.....
But thats not exactly a professional way of going about it, and it will never be reliable (if$x
=9999999....).
Does anyone know how I'd go about doing this??
Answer
Solution:
You need to invoke thedirname
function$x
times, that's called a loop:
$x=6; //amount of sub-folders involved in the path
$dir = dirname(__FILE__);
while(max(0, --$x)) {
$dir = dirname($dir);
}
Answer
Solution:
Recursion is the answer my friend!
function go_up_x_times($path, $x) {
if ($x <= 0) {
return $path; // we're done, yay!
}
return dirname(go_up_x_times($path, $x - 1));
}
go_up_x_times(__FILE__, 5);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: an exception occurred in the driver: could not find driver
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.