Reputation: 1850
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
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
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
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
Reputation: 799580
$userid
doesn't exist within showifuserexists()
. Use global
to tell the function that the variable is found outside.
Upvotes: 1