简体   繁体   English

PHP Foreach数组作为函数错误(foreach in的无效参数……)

[英]PHP Foreach array as a error in function (invalid argument for foreach in…)

Im working on a new minimal Project, but i've got an error, i dont know why. 我正在研究一个新的最小项目,但我有一个错误,我不知道为什么。

Normally, i use arrays after i first created them with $array = array(); 通常,我首先使用$array = array();创建数组后才使用它们$array = array();

but in this case i create it without this code, heres an example full code, which outputs the error: 但在这种情况下,我将在不使用此代码的情况下创建它,以下是完整的示例代码,它会输出错误:

<?php $i = array('demo', 'demo'); $array['demo/demodemo'] = $i; ?>
<?php $i = array('demo', 'demo'); $array['demo/demodemo2'] = $i; ?>

<?php
foreach($array as $a)
{
    echo $a[0] . '<br>';
}

function echo_array_demo() {
    foreach($array as $a)
    {
        echo $a[0] . '<br>';
    }
}

echo_array_demo();
?>

I create items for an array $array and if i call it (foreach) without an function, it works. 我为数组$array创建项目,如果我不使用函数调用它(foreach),则该方法有效。 But if i call in in a function, then the error comes up... 但是如果我在函数中调用,则会出现错误...

I ve got no idea why 我不知道为什么

Thank you... 谢谢...

Functions have their own variable scope . 函数具有自己的可变范围 Variables defined outside the function are not automatically known to it. 在函数外部定义的变量不会自动被其识别。

You can "import" variables into a function using the global keyword. 您可以使用global关键字将变量“导入”到函数中。

function echo_array_demo() {

    global $array;

    foreach($array as $a)
    {
        echo $a[0] . '<br>';
    }
}

Another way of making the variable known to the function is passing it as a reference : 使函数知道变量的另一种方法是将其作为引用传递

function echo_array_demo(&$array) {

    foreach($array as $a)
    {
        echo $a[0] . '<br>';
    }
}

echo_array_demo($array);

Check out the PHP manual on variable scope . 查看有关可变范围PHP手册

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM