Consider the following piece of code:
$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
}
This will work with no issues until it gets to the $test[2], which of course doesn’t have a third element in the array, causing PHP to spit out:
Notice: Undefined offset: 2
Is there a way to get around this besides:
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: Here is what I am actually trying to do:
// 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;
}
Basically for stylistic reasons.
Interesting.
Why don’t you juse do something like this?
If you have a dynamic size of an array, I don’t see why you can’t just pass the entire array into the function instead of having separated arguments.