Jump to content

Looping through string until string is empty


solepixel

Recommended Posts

I'm trying to figure out how to loop through a string similar to a directory structure, such as

 

/boom/stuff/test/file/check/

 

and I want to break off the last chunk on each look, then check that in a database until it finds something in the database, or runs out of string, so it should be:

 

/boom/stuff/test/file/check/ - 0 rows

/boom/stuff/test/file/ - 0 rows

/boom/stuff/test/ - 0 rows

/boom/stuff/ - 0 rows

/boom/ - 0 rows

/ - 0 rows

break; - no rows found at all.

 

 

or

 

/boom/stuff/test/file/check/ - 0 rows

/boom/stuff/test/file/ - 0 rows

/boom/stuff/test/ - 0 rows

/boom/stuff/ - 1 row

break; - found 1 row with /boom/stuff/

 

Does that make sense? Thanks.

Is it in string format?

 

Try this:

<?php

function func ($dir_string) {
while (strlen($dir_string) > 1 && ($last_pos = strrpos($dir_string, "/")) !== false) {
	// database check here
	// return a value if row is not 0. Don't use break!
	$dir_string = substr($dir_string, 0, -1);
	$dir_string = substr($dir_string, 0, strrpos($dir_string, "/") + 1);
}
// return a value if no matches are found
}

?>

You could use the array_pop() function here:

<?php
$str = '/boom/stuff/test/file/check/';
$test_ary = explode('/',trim($str,'/'));
while (!empty($test_ary)) {
	echo '/' . implode('/',$test_ary) . '/<br>';
	$dmy = array_pop($test_ary);
}
echo '/<br>';
?>

 

Ken

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.