0

Access array with same name $userinfo inside a php function

<?php 
    $userinfo['name'] = "bob";
    $userinfo['lastname'] = "johnson";

    function displayinfo() {
//not working 
    echo $userinfo['name']
//global also not working 
    echo global $userinfo['lastname'];

    }
    displayinfo();

?>

how to acess the arrays in the $userinfo var since it has more than one array in the same variable name?

echo $userinfo['name']
//global also not working 
echo global $userinfo['lastname'];

both do not working.

3
  • 3
    Better to pass the array into the function as global is generally discouraged Commented Jul 26, 2019 at 18:49
  • could you give a working example? Commented Jul 26, 2019 at 18:50
  • 1
    echo $GLOBALS['userinfo']['lastname']; Commented Jul 26, 2019 at 19:00

2 Answers 2

5

I recommend passing the variable to the function:

function displayinfo($userinfo) {
  echo $userinfo['name'];
}

$userinfo['name'] = "bob";
$userinfo['lastname'] = "johnson";

displayinfo($userinfo);

See:
PHP global in functions
Are global variables in PHP considered bad practice? If so, why?

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

2 Comments

Ok why it's better than use global?
There are several potential reasons listed here. You can use global, but things might get messy depending on your context.
0

try this, for more details PHP Variable Scope

function displayinfo() {
  global $userinfo;
  echo $userinfo['lastname'];
}

Working example : https://3v4l.org/5l5NZ

2 Comments

This is what I was looking, Thank you, I will implement in my function now.
@OtávioBarreto glad to help 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.