简体   繁体   中英

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();

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. 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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