include_once() & require_once() functions in PHP

Date Published: 26/03/2020Published By: JaiSchool

In this guide, I would like to tell you about include_once() and require_once() functions with examples and the differences between these two functions.

The function include_once() is used to link external PHP files when we have to generate output only one time from the PHP file.

Means include_once generates output at on time. If you link the same file multiple times with incude_once(), you get results only where you link it in the first place.

include_once() function example

test.php

<?php
include_once("result.php");
?>

result.php

<?php
echo "Welcomet to jaischool";
?>
include_once() result

Now, link this external result.php file multiple times in the test.php file. Again, you get result only one time

test.php

<?php
include_once("result.php");
include_once("result.php");
include_once("result.php");
?>

result.php

<?php
echo "Welcomet to jaischool";
?>

Same result when multiple times linked - Image

But by include() function we get results as many times as we link.

And, require_once() is also used to get the result from the PHP page at one time.

include_once() and require_once() differences

But the difference between both of these functions is the same as to include() and require() linking method have which are:-

  • include_once() lets the code execute even the linked file doesn't exist or wrongly linked and in any other error.
  • But, require_once() stops the execution of the code after it if any problem occurs.

You can check it by linking a file that is not available.

Wrongly linked external PHP file with include_once()

test.php

<?php
include_once("result.php");
echo "<br> Code after include once";
?>

result.php

<?php
echo "Welcomet to jaischool.com";
?>
Wrongly linked external PHP file with include_once()

Wrongly linked external PHP file with require_once()

test.php

<?php
require_once("res.php");
echo "<br> Code after require once";
?>

result.php

<?php
echo "Welcomet to jaischool.com";
?>
Wrongly linked external PHP file with require_once()

include() and require() linking methods

By linking any external PHP file with both of these methods you can get the results from the same file as many times as you link that.

Other Related and Helpful Guide
/ foreach() loop in PHP
/ foreach() loop for an associative array in PHP
/ foreach() loop for an ordinary array in PHP
/ How foreach() loop works
/ Get array key by indexing number
/ Can't delete a database in Mysql
/ Update data in the table in Mysql using SQL
/ Delete table in SQL

Publish A Comment

Leave a Reply

Your email address will not be published.