php- 代码让它变小
php- code make it small
我正在尝试使用 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];
}
$path = array();
for($i=0;$i<=7;++$i)
$path[$i]="../uploads/".$_FILES['ufile']['name'][$i];
我反对您目前的编码风格。如果你只是将路径存储在一个数组中,生活会更简单,例如
$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 了解更多关于这里发生的事情的信息
您也可以使用 variable variables:
foreach(range(0,7) as $index){
$varname = "path".$index;
$$varname = "../uploads/".$_FILES['ufile']['name'][$index];
}
不确定你之后想用这些路径做什么,但这是我的做法。我会使用数组的长度,假设它并不总是包含相同数量的文件名。
$paths = array();
for($i = 0; $i < count($_FILES['ufile']['name']); $i++)
{
$paths[] = "../uploads/".$_FILES['ufile']['name'][$i];
}
我正在尝试使用 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];
}
$path = array();
for($i=0;$i<=7;++$i)
$path[$i]="../uploads/".$_FILES['ufile']['name'][$i];
我反对您目前的编码风格。如果你只是将路径存储在一个数组中,生活会更简单,例如
$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 了解更多关于这里发生的事情的信息
您也可以使用 variable variables:
foreach(range(0,7) as $index){
$varname = "path".$index;
$$varname = "../uploads/".$_FILES['ufile']['name'][$index];
}
不确定你之后想用这些路径做什么,但这是我的做法。我会使用数组的长度,假设它并不总是包含相同数量的文件名。
$paths = array();
for($i = 0; $i < count($_FILES['ufile']['name']); $i++)
{
$paths[] = "../uploads/".$_FILES['ufile']['name'][$i];
}