Posted by: prajapatinilesh | February 1, 2008

each() function with multiple files upload

Return the current key and value pair from an array and advance the array cursor (PHP 3, PHP 4, PHP 5)
array each ( array &array )

Returns the current key and value pair from the array array and advances the array cursor. This pair is returned in a four-element array, with the keys 0, 1, key, and value. Elements 0 and key contain the key name of the array element, and 1 and value contain the data.

If the internal pointer for the array points past the end of the array contents, each() returns FALSE.

each() is typically used in conjunction with list() to traverse an array, here’s an example:

If we have files list like:
<input type=”file” name=”pic[]” >
<input type=”file” name=”pic[]” >
<input type=”file” name=”pic[]” >

And Php code like:

$kk = $_FILES[“pic”][“name”];
while(list($key,$value) = each($kk)) {
if(!empty($value)) {
$filename = $value;
$ext =strtolower(substr($filename, strrpos($filename, ‘.’) + 1));
if(in_array($ext,$AllowedExt,TRUE)) {

}else{ $allowUpload = false; }

if($allowUpload) {
if($name!=”” or $designation!=”” or $type!=”” or $sex!=”” or $country!=”” ) {
$q=”INSERT INTO “. TB_PER_FRIENDS. “( `name` ,`designation` ,`sex` ,`b_date` ,`city` ,`country` ,`fr_since` ,`about_it` ,`net_friend` )
VALUES (‘”.$name.”‘, ‘”. $designation.”‘, ‘”.$sex.”‘, ‘”.$b_date.”‘,'”. $city.”‘, ‘”.$country.”‘, ‘”.$since.”‘, ‘”.$about.”‘,'”.$type.”‘)”;

if(isset($id) and $id>0) {
while(list($key2,$value2) = each($kk)) {
if(!empty($value2)) {
echo $filename2 = $value2;
$ext2 =substr($filename2, strrpos($filename2, ‘.’) + 1);
$add2 = “../”.PER_SITE_FOLDER.”/friend_img/”.$nm2;
if(move_uploaded_file($_FILES[“pic”][“tmp_name”][$key2], $add2)) {
//GD Library function
$queryInsert=”insert into”.TB_PER_FR_PHOTO. “(fr_id,fr_pic) values($id,'”.$nm2.”‘)”;
}else {
$uploaded=”But Image Does not uploaded”;
$msg=”Successfully Inserted”.$uploaded;
}else{$msg=”Error:Doesn not Inserted”;}
$msg=”You can not blank complsory field”;
$msg=”You can upload only jpg,jpeg,gif,png,bmp files”;

Means in above example we are using first each in while loop during checking file extensions and then second each for inserting records.
At this time we must need to use reset funcation.
After each() has executed, the array cursor will be left on the next element of the array, or past the last element if it hits the end of the array. You have to use reset() if you want to traverse the array again using each.



  1. code is very useful. thanks nilesh

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s


%d bloggers like this: