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.

Otávio Barreto
  • 1,536
  • 3
  • 16
  • 35

2 Answers2

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?

showdev
  • 28,454
  • 37
  • 55
  • 73
0

try this, for more details PHP Variable Scope

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

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

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20