Skip to content
PHP Logo

What is the best practice for creating a function in PHP to check a variable and end the script with a custom error message if the variable is not true?

When creating a function in PHP to check a variable and end the script with a custom error message if the variable is not true, it is best practice to use an if statement to check the variable and then use the die() function to end the script with a custom error message if the condition is not met.

php
function checkVariable($variable) {
    if (!$variable) {
        die("Error: Variable is not true.");
    }
}

// Example of using the function
$testVariable = false;
checkVariable($testVariable);