处理丢失的数组偏移量

qua*_*oup 2 php

考虑以下代码:

$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
}
Run Code Online (Sandbox Code Playgroud)

这将无问题,直到它到达$ test [2],当然在数组中没有第三个元素,导致PHP吐出:

Notice: Undefined offset: 2
Run Code Online (Sandbox Code Playgroud)

有没有办法解决这个问题:

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
}
Run Code Online (Sandbox Code Playgroud)

随着每个$ 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;
}
Run Code Online (Sandbox Code Playgroud)

基本上是出于文体方面的原因.

Bar*_*tek 6

有趣.

你为什么不这样做?

foreach($tests as $test) {
   test($test);
}

function test($test) {
   // loop through $test to get all the values as you did originally
}
Run Code Online (Sandbox Code Playgroud)

如果你有一个数组的动态大小,我不明白为什么你不能只将整个数组传递给函数而不是分开的参数.