views:

40

answers:

1

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

+2  A: 

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.

Pekka
sure... how can i forget this :D Thank you !
ahmet2106