Jump to content

[SOLVED] Arrays Inside a Function Not Working


Mzor

Recommended Posts

This is frustrating me... I'll let this piece of code do the explaning ofr me:

 

<?php

$test = array ('one', 'two');

$test['one'] = 1;
$test['two'] = 2;

function oneAndTwo(){
  echo $test['one'] . '<br />';
  echo $test['two'];
}

oneAndTwo();

?>

 

This returns the error:

 

Notice: Undefined variable: test in C:\wamp\www\test.php on line 11

 

 

Notice: Undefined variable: test in C:\wamp\www\test.php on line 12

 

Now, when I echo the variable $test['one'] outside of the function, it works just fine. hy is it not working when I echo it using a function?

Link to comment
Share on other sites

This is to do with variable scope. Functions have their own variable scope.

 

To be able to use a variable set outside of a function you can, either define the variable within the function as global, eg:

 

$myvar = 'hello';

function foo()
{
    global $myvar;

    echo $myvar;
}

 

Or pass the variable to the function

$myvar = 'hello';

function foo($var)
{
    echo $var;
}

 

The same applies to variables set within a function. In order to retrieve variables that were defined within a function you can either define it as global (as shown above) or return the the value the variable, eg:

function add_up($n, $y)
{
    $result = $n + $y;

   return $result;
}

$result = add_up(5, 6);

// OR

echo add_up(5, 6);

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.