php

How to Use alert() Function in PHP

PHP is widely used for developing interactive and dynamic websites and web applications. It provides numerous functions to developers for improving the functionality of the websites. One such function is the alert() function in PHP which is used to display pop-up messages on websites. This function is used to prompt users while inputting the information on the websites. The alert box contains the OK button, that allows users to dismiss the alert box.

In this guide, we will discuss the usage, and syntax of the PHP alert() function with sample examples.

What is an alert() Function in PHP?

The alert() function is used to pop up the message on the screen. This function displays a simple dialog box containing a message to the user. When you call the alert() function in your PHP code, it interrupts the normal flow of the program and halts its execution until the user interacts with the dialog box.

Syntax

The basic syntax for using the alert() function is as follows:

alert("Message")

The alert() function only accepts one argument, Message that will be displayed on the screen in the pop-up, this argument can be a string or a variable that holds a string value.

How to Use an alert() Function in PHP?

The following examples demonstrate the alert() function usage in PHP.

Example 1

The following PHP code demonstrates the usage of the alert() function, which is used in the echo statement to display a pop-up on the screen:

<?php
echo '<script>alert("Welcome to Linuxhint")</script>';
?>

Example 2

Consider another example that defines a custom function called function_alert(). This function takes a message as an argument and displays an alert box on the screen with the provided message:

<?php
function function_alert($message) {
   echo "<script>alert('$message');</script>";
}

// Function call
function_alert("Welcome to LinuxHint");

?>

Bottom Line

The alert() function in PHP is used to display the message on the websites and to interact with the users. It enables developers to provide timely and relevant information to users, enhancing the overall functionality and usability of their websites or web-based systems. We have demonstrated the usage of the alert() function with sample codes in the above section of the guide.

About the author

Zainab Rehman

I'm an author by profession. My interest in the internet world motivates me to write for Linux Hint and I'm here to share my knowledge with others.