July 26, 2017

Core PHP: Include & Require (5.19)

include vs require


The require statement is identical to include, the exception being that, upon failure, it produces a fatal error.
When a file is included using the include statement, but PHP is unable to find it, the script continues to execute.
In the case of require, the script will cease execution and produce an error.

Use require when the file is required for the application to run.
Use include when the file is not required. The application should continue, even when the file is not found.

Core PHP: Include & Require (5.18)

include


Using this approach, we have the ability to include the same header.php file into multiple pages.

<html>
  <body>

  <?php include 'header.php'; ?>

  <p>This is a paragraph</p>
  </body>
</html>

Result:
Example: include


Files are included based on the file path.
You can use an absolute or a relative path to specify which file should be included.

Core PHP: Include & Require (5.17)

include


The include and require statements allow for the insertion of the content of one PHP file into another PHP file, before the server executes it.
Including files saves quite a bit of work. You can create a standard header, footer, or menu file for all of your web pages. Then, when the header is requiring updating, you can update the header include file only.

Assume that we have a standard header file called header.php.

<?php
  echo '<h1>Welcome</h1>';
?>

Use the include statement to include the header file in a page.

<html>
  <body>

  <?php include 'header.php'; ?>

  <p>Some text.</p>
  <p>Some text.</p>
  </body>
</html>

Core PHP: The continue Statement (5.16)

The continue Statement


When used within a looping structure, the continue statement allows for skipping over what remains of the current loop iteration. It then continues the execution at the condition evaluation and moves on to the beginning of the next iteration.

The following example skips the even numbers in the for loop:
for ($i=0; $i<10; $i++) {
  if ($i%2==0) {
    continue;
  }
  echo $i . ' ';
}

//Output: 1 3 5 7 9

You can use the continue statement with all looping structures.

Core PHP: The break Statement (5.15)

The break Statement


As discussed in the previous lesson, the break statement is used to break out of the switch when a case is matched.
If the break is absent, the code keeps running. For example:

$x=1;
switch ($x) {
  case 1:
    echo "One";
  case 2:
    echo "Two";
  case 3:
    echo "Three";
  default:
    echo "No match";
}

//Outputs "OneTwoThreeNo match"

Break can also be used to halt the execution of for, foreach, while, do-while structures.
The break statement ends the current for, foreach, while, do-while or switch and continues to run the program on the line coming up after the loop.
A break statement in the outer part of a program (e.g., not in a control loop) will stop the script.