Otávio Barreto
Otávio Barreto

Reputation: 1568

Access array inside a php function

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.

Upvotes: 0

Views: 1480

Answers (2)

showdev
showdev

Reputation: 29168

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?

Upvotes: 5

Rakesh Jakhar
Rakesh Jakhar

Reputation: 6388

try this, for more details PHP Variable Scope

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

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

Upvotes: 0

Related Questions