Eksik dizi uzaklıklar Taşıma

0 Cevap

Aşağıdaki kod parçasını düşünün:

$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
}

Dışarı tükürmek için PHP neden, [2], tabii ki dizideki üçüncü bir öğe yok $ testi alır kadar bu hiçbir sorunları ile çalışır:

Notice: Undefined offset: 2

Bunun yanında aşmanın bir yolu var mı:

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
}

Which gets unwieldy as the size of each $test array gets bigger. Or should I just ignore the notice after all?

EDIT: İşte ben aslında yapmak çalışıyorum budur:

// 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;
}

Temelde üslup nedenlerle.

0 Cevap