.NET Path.Combine() in PHP

I’m the type of person who prefers to do things in a way that I perceive as the proper or correct way. While this tends to make things take a bit longer to accomplish, I feel the result ends up being better overall. One such thing I noticed is that file and path handling in PHP was missing a function I used quite a bit when writing C# code. In C# there is a Path.Combine() function that appends two file paths together to form one complete path without having to care what the beginning character and ending character of the two paths are. I wrote up a little function in PHP to mimic what happens.

//take a path and/or a filename and combine them into one file path
function filePathCombine($path1, $path2)
{
  $completedPath = '';

  if(substr($path1, strlen($path1) - 2, strlen($path1) - 1) !== DIRECTORY_SEPARATOR)
  {
		$completedPath = $path1 . DIRECTORY_SEPARATOR;
  }
  else
  {
		$completedPath = $path1;
  }

  if(substr($path2, 0, 1) !== DIRECTORY_SEPARATOR)
  {
		$completedPath .= $path2;
  }
  else
  {
		$completedPath .= substr($path2, 1, strlen($path2) - 1);
  }

  return $completedPath;
}

Looking through the code you will notice DIRECTORY_SEPARATOR, which is a global PHP constant. While it isn’t needed considering using / instead of \ would work on Windows and Linux, I thought it best to try to stay with my idea on how to do things the proper way.

This entry was posted in General and tagged , , , , , . Bookmark the permalink.