php-代码使它变小

时间:2015-02-28 06:12:41

标签: php image-uploading

我正在尝试使用for或while循环使这段代码变小。它正在使用以下代码,我只想让它变小。 'ufile'是输入名称。

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];

}

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

我会反对您当前的编码风格。如果你只是将路径存储在一个数组中,那么生活会更简单,例如

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

然后你可以这样做:

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

但是要回答你的问题,你可以做一些类似的事情,这非常相似:

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

有关此处发生的更多信息,请参阅extract doc page

答案 2 :(得分:1)

您也可以使用variable variables

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

答案 3 :(得分:0)

不确定之后你想对这些路径做什么,但这是我的理由。我会使用数组的长度,假设它不总是包含相同数量的文件名。

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