Jump to content

returning arrays in loop


visevo

Recommended Posts

I'm trying to create a series of functions, when activated:

 

a. scans a target directory for jpg's -> returns file names to an array

b. takes those file names and stripes the .jpg from them -> return file name, extension, and full filename

c. inserts said file names into a MySQL database

 

Here's the problem: The second function won't loop on the return array('name' => $name), it just does it once.

Code:

Function 1 (of 3)

function scanJpg($phpath){
$dir = opendir($phpath);

while(false !== ($file = readdir($dir))){
	if($file != "." && $file != ".."){
		if(!is_dir($phpath.$file)){
		$results[] = $file;
		}
	}
}
closedir($dir);
return $results;
}

// returns
// Array ( [0] => lakeonrefuge.jpg [1] => shasta04.jpg [2] => carly_lol.jpg [3] => beach_adventures_florence.jpg [4] => beach_adventures.jpg [5] => Beach-0168.jpg )

 

function 2

function stripJpg($jpgs,$phpath){
foreach($jpgs as $jpg){
	$ext = strrchr($jpg, '.');
		if($ext !== false)
		{
			$name = substr($jpg, 0, -strlen($ext));
			echo $name."<br />";
			echo $jpg."<br />";
			echo $ext."<br /><br />";
			return array(
				'name' => $name,
				'filename' => $jpg,
				'ext' => $ext
			);
		}

}
}


## $jpgs = scanJpg($phpath);
## print_r(stripJpg($jpgs,$phpath));
##
## returns the following
## Array ( [name] => lakeonrefuge [filename] => lakeonrefuge.jpg [ext] => .jpg )

 

What am I overlooking? Thanks in advance!

Link to comment
Share on other sites

The function is not looping through all the array elements because after the first array element is processed, your function is 'returning'

 

return array(
				'name' => $name,
				'filename' => $jpg,
				'ext' => $ext
			);

 

Instead of writing return in each iteration, just assign the results in another array and return that array after the entire parameter array is looped through.

 

Like this:-

foreach($jpgs as $jpg)
{
     $ext = strrchr($jpg, '.');
     if($ext !== false)
     {
    $name = substr($jpg, 0, -strlen($ext));
    echo $name."<br />";
    echo $jpg."<br />";
    echo $ext."<br /><br />";
    $value[] =  array(
				'name' => $name,
				'filename' => $jpg,
				'ext' => $ext
			);
     }
}
return $value;

Link to comment
Share on other sites

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.