Abhay Naik
Abhay Naik

Reputation: 405

php- code make it small

I am trying to make this code small using for or while loop . It is working with the following code,I just want this to be small. 'ufile' is the input name.

if (!$_FILES['ufile']['name'][0]) 

{
    echo "Upload 1st file";

}

else

{

    // can this be in a for loop???
    $path1= "../uploads/".$_FILES['ufile']['name'][0];

    $path2= "../uploads/".$_FILES['ufile']['name'][1];

    $path3= "../uploads/".$_FILES['ufile']['name'][2];

    $path4= "../uploads/".$_FILES['ufile']['name'][3];

    $path5= "../uploads/".$_FILES['ufile']['name'][4];

    $path6= "../uploads/".$_FILES['ufile']['name'][5];

    $path7= "../uploads/".$_FILES['ufile']['name'][6];

    $path8= "../uploads/".$_FILES['ufile']['name'][7];

}

Upvotes: 1

Views: 72

Answers (4)

Alireza Fallah
Alireza Fallah

Reputation: 4607

You can use variable variables as well :

foreach(range(0,7) as $index){
    $varname  = "path".$index;
    $$varname = "../uploads/".$_FILES['ufile']['name'][$index];
}

Upvotes: 1

Fabian Küng
Fabian Küng

Reputation: 6183

Not sure what you want to do with those paths afterwards but here is my go at it. I would use the length of the array, assuming it doesn't always contain the same amount of file names.

$paths = array();
for($i = 0; $i < count($_FILES['ufile']['name']); $i++)
{
    $paths[] = "../uploads/".$_FILES['ufile']['name'][$i];
}

Upvotes: 0

rjdown
rjdown

Reputation: 9227

I would advise against your current coding style. Life would be simpler if you just stored the paths in an array, e.g.

 $paths[1] = "../uploads/" . $_FILES['ufile']['name'][0];
 $paths[2] = "../uploads/" . $_FILES['ufile']['name'][1];

Then you could do something like this:

$paths = array();
for ($i = 0; $i <= 7; $i++) {
    $paths[$i + 1] = $_FILES['ufile']['name'][$i];
}

But to answer your question, you can do something like this instead, which is very similar:

$paths = array();
for ($i = 0; $i <= 7; $i++) {
    $paths['path' . ($i + 1)] = $_FILES['ufile']['name'][$i];
}
extract($paths);

See the extract doc page for more info about what's going on here

Upvotes: 1

user1627167
user1627167

Reputation: 339

$path = array();
for($i=0;$i<=7;++$i)
    $path[$i]="../uploads/".$_FILES['ufile']['name'][$i];

Upvotes: 1

Related Questions