The only difference is that the 2nd is written within a function and returns instead of echo. What is the problem?

<?php
 jcarousel_add('tango');
    drupal_add_js (
      '$(document).ready(function(){
         $("#carousel-cars").jcarousel();
  }
 ); ',
      'inline'
 );
 
 echo getcwd();
 echo "<div id=\"carousel-cars-horiz\">";
 echo "<ul id=\"carousel-cars\"  class=\"jcarousel-skin-tango\">";
 
 
 
 $pic = NULL;
 $url = "./sites/all/modules/img/Images/";
 $handle = opendir($url);
 while (false !== ($file = readdir($handle))) { 
  if($file != '.' && $file != '..' && $file != 'Thumbs.db') {
  
    $str= "<li><img src =\"" . $url.$file . "\" width=90 height=80/></li>";
    
    echo $str;
  }
 }
 
 echo "</ul>";
 echo "</div>";
?>

Following is the second program

function jcrl($catname)	{

	jcarousel_add('tango');
	drupal_add_js (
      '$(document).ready(function(){
         $("#carousel-cars").jcarousel();
  }
 ); ',
      'inline'
 );
	 
	$renderjcrl =NULL;
	
	$renderjcrl = $renderjcrl . '<div id=\"carousel-cars-horiz\">';
	$renderjcrl = $renderjcrl . '<ul id=\"carousel-cars\"  class=\"jcarousel-skin-tango\">';
	 
	 
	 
	$pic = NULL;
	$url = "./sites/all/Categories/" . $catname . "/";
	
	$handle = opendir($url);
	while (false !== ($file = readdir($handle))) { 
		if($file != '.' && $file != '..' && $file != 'Thumbs.db') {
	 
			$renderjcrl =  $renderjcrl . "<li><img src =\"" . $url.$file . "\" width=90 height=80/></li>";
		}
	}
	
	$renderjcrl = $renderjcrl .  '</ul>';
	$renderjcrl = $renderjcrl .  '</div>';
	return $renderjcrl;
 
}

on the non-working code, these:

$renderjcrl = $renderjcrl . '<div id=\"carousel-cars-horiz\">';
$renderjcrl = $renderjcrl . '<ul id=\"carousel-cars\" class=\"jcarousel-skin-tango\">';

will end up sending

id=\"....\"

to the browser - meaning, the browser will get the backslash AND the double quotes because (unlike your first code) your overall string is enclosed in apostrophes, NOT in double quotes. You need the back slashes if you had double quotes around the div.

So you need to use either:
a.enclose the div in double quotes

$renderjcrl = $renderjcrl . "<div id=\"carousel-cars-horiz\">";
$renderjcrl = $renderjcrl . "<ul id=\"carousel-cars\" class=\"jcarousel-skin-tango\">";

OR:
b. leave the apostrophes around the div, but get rid of the backslashes

$renderjcrl = $renderjcrl . '<div id="carousel-cars-horiz">';
$renderjcrl = $renderjcrl . '<ul id="carousel-cars" class="jcarousel-skin-tango">';