考虑以下代码:
$tests = array(
array ("a", "b", "c"), array ("1", "2", "3"), array ("!", "@")
);
foreach ($tests as $test)
test($test[0], $test[1], $test[2]);
function test($param1, $param2, $param3) {
// do whatever
}
在到达 $test[2] 之前,这不会出现任何问题,当然,数组中没有第三个元素,导致 PHP 吐出:
Notice: Undefined offset: 2
除了以下方法之外,还有其他方法可以解决这个问题:
foreach ($tests as $test) {
if (count($x) == 2)
test($test[0], $test[1]);
else
test($test[0], $test[1], $test[2]);
}
function test($param1, $param2, $param3=null) {
// do whatever
}
随着每个 $test 数组的大小变大,这会变得很笨拙。 或者我到底应该忽略这个通知吗?
编辑:这是我实际上想做的事情:
// wanted this:
function validate() {
$pass = true;
$rules = array (array ('field1', '!=', 'banana'),
array('field2', 'notempty')
);
for ($i=0; $i<count($rules) && $pass; $i++)
$pass = check($rules[$i][0], $rules[$i][1], $rules[$i][1]);
return $pass;
}
function check($field, $operator, $expected) {
$value = $this->getValue($field);
switch ($operator) {
case '!=':
$pass = ($value != $expected);
break;
case '==':
$pass = ($value == $expected);
break;
case 'empty':
$pass = empty($value);
break;
default:
$pass = !empty($value);
break;
}
return $pass;
}
//instead of
function validate() {
$pass = true;
for ($i=0; $i<count($rules) && $pass; $i++)
$pass = check($rules[$i]);
return $pass;
}
function check($check) {
$value = $this->getValue($check[0]);
switch ($check[1]) {
case '!=':
$pass = ($value != $check[2]);
break;
case '==':
$pass = ($value == $check[2]);
break;
case 'empty':
$pass = empty($value);
break;
default:
$pass = !empty($value);
break;
}
return $pass;
}
基本上是出于风格原因。
最佳答案
有趣。
你为什么不做这样的事情呢?
foreach($tests as $test) {
test($test);
}
function test($test) {
// loop through $test to get all the values as you did originally
}
如果您有一个动态大小的数组,我不明白为什么您不能将整个数组传递到函数中,而不是使用单独的参数。
关于php - 处理丢失的数组偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3159741/