- PHP

How to End PHP code

See how to end a block of PHP code and how to abort further scripts on the page.

Method 1: End PHP block with the ?> tag.

<?php // starting PHP block

    // your code

// ending PHP block ?>

Example:

<?php 

    // PHP code

    echo 2 + 2;

?>

<!-- HTML CODE -->

<br>

2 + 2

Output:

4

2 + 2

Method 2: Prevent execution of code below with die() function.

The die() function allows you to terminate the execution of the script at any time. Thanks to it, the code which will be placed below will not be executed.

<?php

// some code

die();

// some code that won't be executed

?>

Example:

<?php

$animals = ['dog', 'something else', 'something else 2', 'something else 3'];

echo '<b>First animal:</b> ' . $animals[0] . '<br><br>';

// Let's say I don't want to execute the code below. To end the script here, I can use the die() function.

die();

// Code below won't be executed now!

echo '<b>All animals:</b><br>';

echo '<ul>';

foreach($animals as $animal) {
    echo '<li>' . $animal . '</li>';
}

echo '</ul>';

Output:

First animal: dog