5

I was wondering if i have a function like this:

function isAdmin ($user_id) {

    $admin_arr = array(1, 2);

    foreach ($admin_arr as $value) {

        if ($value == $user_id) {
            return true;
        }
    }

    return false;
}

Could i make an array outside of that function as a global array and use it inside the function without sending it through as a parameter, also instead declaring a new admin array inside the function as i just did above? How would i do this?

Regards, Alexander

4
  • Why do you want this? It is possible, but not recommended. Commented May 6, 2011 at 13:22
  • Yes you could, but avoid globals as much as possible. What is the problem with passing it to the function? Commented May 6, 2011 at 13:23
  • I think you can use define() to make it as a constant if that array is actually a constant. Commented May 6, 2011 at 13:28
  • @albb: you cannot define constant array Commented May 6, 2011 at 13:30

3 Answers 3

12

To answer literal question:

// Global variable
$admin_arr = array(1, 2);

function isAdmin ($user_id) {

    // Declare global
    global $admin_arr;

    foreach ($admin_arr as $value) {

        if ($value == $user_id) {
            return true;
        }
    }

return false;
}

Documentation here: http://php.net/manual/en/language.variables.scope.php

To answer the REAL question: Avoid global at all costs. You are introducing a plethora of error prone code into your application. Relying on global variables is entering a world of pain and makes your functions less useful.

Avoid it unless you absolutely see no other way.

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

Comments

1

you have to do this with the global keyword

here an example

$arr = array('bar');
function foo() {
    global $arr;
    echo array_pop($arr);
}
foo();

Comments

1

I concur with others that this is not the preferred way to do it, and you should be passing the array as a parameter, but I just wanted to point out the $GLOBALS[] superglobal array, which I find more readable than the global keyword.

$global_array = array(1,2,3);

function myfunc()
{
  echo $GLOBALS['global_array'][0];
  print_r($GLOBALS['global_array']);
}

Comments

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.