0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.