visevo Posted April 27, 2011 Share Posted April 27, 2011 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 https://forums.phpfreaks.com/topic/234811-returning-arrays-in-loop/ Share on other sites More sharing options...
saurabhx Posted April 27, 2011 Share Posted April 27, 2011 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 https://forums.phpfreaks.com/topic/234811-returning-arrays-in-loop/#findComment-1206711 Share on other sites More sharing options...
visevo Posted April 27, 2011 Author Share Posted April 27, 2011 Awesome. Solved it. Thanks! Link to comment https://forums.phpfreaks.com/topic/234811-returning-arrays-in-loop/#findComment-1206714 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.