是否有更简单的方法来更改单个数组值?

时间:2011-08-14 22:54:57

标签: php arrays post if-statement foreach

如果$names的{​​{1}}值为空,我正在尝试将$urls数组值默认为并行$_POST[]值。 (这是基于假设空$names将返回空的假设,如果我错了,请有人纠正我。)

这是我的代码:

$_POST[]

我考虑过使用$urls = array(1 => $_POST['url_1'], 2 => ['url_2'], 3 => $_POST['url_3'], 4 => $_POST['url_4'], 5 => $_POST['url_5']); $names = array(1 => $_POST['name_1'], 2 => ['name_2'], 3 => $_POST['name_3'], 4 => $_POST['name_4'], 5 => $_POST['name_5']); if(empty($names[1])) { $names[1] = $_POST['url_1']; } if(empty($names[2])) { $names[2] = $_POST['url_2']; } if(empty($names[3])) { $names[3] = $_POST['url_3']; } if(empty($names[4])) { $names[4] = $_POST['url_4']; } if(empty($names[5])) { $names[5] = $_POST['url_5']; } 循环,但我真的不知道它是如何工作的,因为每个单独的数组值例如如果为空,则foreach()必须设置为$names[1]

非常感谢任何建议,意见或其他信息:)!

4 个答案:

答案 0 :(得分:4)

for ($i = 1; $i <= 5; $i++) {
    $names[$i] = !empty($_POST['name_' . $i]) ? $_POST['name_' . $i] : $_POST['url_' . $i];
}

答案 1 :(得分:2)

for ($i = 1; $i <= 5; $i++) {
    if (empty($names[$i])) {
        $names[$i] = $_POST['url_' . $i];
    }
}

但请注意,您还需要检查$_POST['url_' . $i']是否也存在isset()检查

答案 2 :(得分:2)

foreach ($names as $k=>$v){
if(empty($v)){
 $names[$k] =$urls[$k];
// or  $names[$k] = $_POST['url_' . $k'];
}
}

答案 3 :(得分:0)

$urls = array(1 => $_POST['url_1'], $_POST['url_2'], $_POST['url_3'], $_POST['url_4'], $_POST['url_5']);
$names = array(1 => $_POST['name_1'], $_POST['name_2'], $_POST['name_3'], $_POST['name_4'], $_POST['name_5']);

for ( $c = 1; $c <= 5; $c++ )
{
  if(empty($names[$c])) 
  { 
    $postKey = 'url_'.$c;
    $names[$c] = $_POST[$postKey]; 
  }
}