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?

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

?>

Archived

This topic is now archived and is closed to further replies.

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