dongque1646 2011-07-13 20:02
浏览 30
已采纳

将具有未知大小的数组传递给函数

I've been scouring Google for an answer to this problem I'm having and have come up empty so far.

Basically, I'm creating an array of error messages, passing them as an array to a function, looping through the values, formatting and then returning them. For some reason the values do not get passed and I get an "Invalid argument supplied for foreach()" error.

//Create the error array
$error = 0;
$errorArray = array();
if(empty($_POST['amount']))
{
    $error = 1;
    array_push($errorArray,"Amount is required");
}

//Error Function
function makeErrors($err)
{
    $output = 'ul'; 
    foreach($err as $v)
    {
        $output .= '<li>'.$v.'</li>';
    }
    $output .= '</ul>';
    return $output;
}

//Show the result
if($error == 1)
{
    $theErrors = makeErrors($errorArray);
    echo $theErrors;
}

If I just do a plain old print_r on $errorArray I get the expected value, so there's something lost when passing the array to the function. Any suggestions would be much appreciated.

  • 写回答

1条回答 默认 最新

  • dsagzmosl32217092 2011-07-13 20:07
    关注

    That should work perfectly, you might want to wrap the first "ul" in <> though.

    Just tested it and its working fine here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?