I have a PHP code like this:
<?php
if($condition) {myFunction();};
?>
<html>
<head>
</head>
<body>
Some HTML code
<?php
function myFunction() {
print "Print some new code";
};
?>
</body>
</html>
When the myFunction is called, the new code is printed before the first html tag.
How can I change that behaviour and print, say, after "Some HTML code".
Thanks!
You have to call the function where you want to print not define it there.
<?php
function myFunction() {
print "Print some new code";
};
?>
<html>
<head>
</head>
<body>
Some HTML code
<?php
if($condition) {myFunction();};
?>
</body>
</html>
--EDIT-- for comment
Check the conditions in both places, or separate your logic and content
<?php
function myFunction() {
return "Print some new code";
}
$somecontent = '';
$morecontent = '';
if($condition) {
$somecontent = myFunction();
}
else{
$morecontent = 'some more content';
}
?>
<html>
<head>
</head>
<body>
<?php
echo $morecontent;
?>
Some HTML code
<?php
echo $somecontent;
?>
</body>
</html>
The function is being run when the statement returns true, so it does print "Print some new code"; right there.
In order to get the new code within the body tag, have the if statement in there.
As well, If you move the function outside of the rendered HTML (like below) then it keeps the markup separate from the logic.
<?php
function myFunction() {
print "Print some new code";
};
?>
<html>
<head>
</head>
<body>
Some HTML code
<?php
if($condition) {myFunction();};
?>
</body>
</html>
Two things you should remember for working with functions.
1- Define it first
<?php
function function_name () {
// do something
}
2- Call it secondly
function_name();
And remember function will return whatever it has where you'll call it, not where you have defined it. So in your case as you've inverted the game the result is inverted.
Here is the remedy:
<?php
function myFunction() {
return "Print some new code";
};
?>
<html>
<head>
</head>
<body>
Some HTML code
<?php
if ($condition) {
echo myFunction();
}
</body>
</html>