Reputation: 4578
here is my code :
abc.php
<?php
for($i=1;$i<4;$i++){
echo include_once('text.php');
echo include('text.php');
}
?>
text.php
Hello World
Returns output :
Hello World1Hello World11Hello World11Hello World1
What is 1
in above output ?
Upvotes: 1
Views: 2158
Reputation: 1
Take out the echo from in front of include & include_once.
This is Wrong
echo include_once('text.php');
echo include('text.php');
Placing echo in front these functions will only return whether or not the file was found and included. jacek-kowalewski pointed this out earlier. Although saying that include automatically echoes could be somewhat confusing. include() injects the code into the main file wherever the function is called. The contents of the included file could be just text OR it could be more php code. If it is more code it will not echo anything unless the echo function is invoked.
I don't understand using include and include_once for the same file? - text.php
Using include_once() AND include() together creates a situation where one cancels the the other. include_once('text.php') means that text.php can only be included one time in the main script. Include on the other hand will allow text.php to included as many times as the function is called. But in this case text.php cannot be called multiple time because include_once() has already set the rule for only once. See Includes Canceling
If there is a string of text that you want to output two times consecutively to the webpage then you should place the echo command inside of the text.php file:
echo 'My String of Text';
echo 'My Second String of Text';
Then place include_once into your main script:
include_once('text.php');
You may want to rewrite your script like this:
for($i=0;$i<5;$i++){
echo 'Text '.$i.'<br />';
$i =$i+1;
echo 'Text '.$i.'<br />';
}
Your output will be:
Text 0
Text 1
Text 2
Text 3
Text 4
Text 5
Upvotes: 0
Reputation: 2851
Here are all the iterations:
1) include_once: Hello World1 // include file echo automaticaly, and echo 1 (success)
include: Hello World1 // include file echo automaticaly, and echo 1 (success)
2) include_once: 1 // included already only success...
include: Hello World1
3) include_once: 1 // included already only success...
include: Hello World1
4) include_once: 1 // included already only success...
include: Hello World1
Output: Hello World1Hello World11Hello World11Hello World1
.
As metndioned in comments, include automaticaly echo the code, so echo include
echo the file, and echo the return value of include function :). Which is true = 1.
Upvotes: 1
Reputation: 13665
The 1 is the return value of the include_once call. If you include a file that does not exist with include_once, the return result will be false. If you try to include that same file again with include_once the return value will be true.
Upvotes: 0