Tom Granot
Tom Granot

Reputation: 1850

Printing a variable in PHP does not work

I've got this piece of code:

<?php
  $userid = $me['id'];
  function showifuserexists() {
?>
<html>
  <head></head>
<body>
  <a href="file.php?element1=aaa&userid=<?php print $userid; ?>">
</body>
</html>
<?php
} 
?>

For some reason I can't get the php $userid to show up in the html link. I've tried echo too. Help?

Upvotes: 1

Views: 4603

Answers (4)

Monisha
Monisha

Reputation: 11

You can't acceess the variable $userid inside the function. You can get the value by passing the variable as a function parameter.

Example code:

<?php
  $userid = 1;
  function showifuserexists($userid) {
?>
  <html>
  <head></head>
  <body>
      <a href="file.php?element1=aaa&userid=<?php echo $userid?>" >
  </body>
  </html>
<?php
}
showifuserexists($userid);
?>

Hope this will help you.

Upvotes: 1

Aron Rotteveel
Aron Rotteveel

Reputation: 83223

You are most likely a lot better off when not using an inline-created function for simple behaviour like this. Just use a simple if-statement:

<?php
    $userid = $me['id'];
    if (null !== $userid) {
?>
<html>
  <head></head>
<body>
  <a href="file.php?element1=aaa&userid=<?php print $userid; ?>">
</body>
</html>
<?php
    }
?>

Sidenote: the problem in your original post is that - like many others have already explained - $userid is defined outside the scope of your function, making it unavailable within the scope of this function.

Upvotes: 2

Ross
Ross

Reputation: 17987

You should read up on variable scope.

$userid in your function is not the same as $userid outside of your function - it has a different scope. You could make the variable global, but that's not really good practice, especially in this context.

I'm not really sure what you are trying to achieve; but I guess..

function showifuserexists($userid=null) {
    echo '<a href="file.php?element1=aaa&userid=' . $userid . '"> ... </a>';
    // functions should *generally* return output, but for examples sake
}

then you would do:

showifuserexists($me['id']);

for example. But your requirements aren't really that clear.

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799580

$userid doesn't exist within showifuserexists(). Use global to tell the function that the variable is found outside.

Upvotes: 1

Related Questions