PHP: includeIfExists

posted in: Uncategorized | 0

This snippet of code was inspired by a tweet by Brad Frost (@brad_frost).

So, upon seeing this, I decided to throw something together. I took the Count Lines of Code function, which was very similar in concept, and modified it to meet these requirements.

function includeIfExists($path,$filename) {
   $found = "false";
   $items = glob(rtrim($path, '/') . '/*');

   foreach($items as $item) {

       if (is_file($item)) {
           if(substr( $item, ( strrpos( $item, "/" ) +1 ) ) == $filename){
				$found = "true";
				include $item;
       } else if (is_dir($item)) {
           if(includeIfExists($item,$filename) == "false"){
		   } else {
				$found = "true";

	return $found;


This function will return a literal string of “true” or “false” if it is found, so if you wanted to, you could do some kind of logic for if the file isn’t included.

My name is Andrew McGivery. I currently work full time as an application developer at Manulife Financial in Canada. My current passion is building and leading highly engaged teams where employee happiness, learning, and growth is a priority.

Leave a Reply