Introduction:
PHP, a widely used server-side scripting language, comes with a variety of built-in functions that provide functionality for common tasks.
Here’s a list of some essential PHP built-in functions, categorized by their functionality:
Returns the length of a string.
$length = strlen("Hello, World!");
Replaces a substring with another substring in a string.
$new_string = str_replace("old", "new", "This is the old string.");
Returns a portion of a string.
$substring = substr("Hello, World!", 0, 5);
Returns the number of elements in an array.
$count = count($my_array);
Adds one or more elements to the end of an array.
array_push($my_array, "new element");
Removes and returns the last element of an array.
$last_element = array_pop($my_array);
Returns the absolute value of a number.
$absolute_value = abs(-10);
Generates a random number.
$random_number = rand(1, 100);
Rounds a floating-point number to the nearest integer.
$rounded_number = round(3.14);
Reads the content of a file into a string.
$content = file_get_contents("example.txt");
Writes a string to a file.
file_put_contents("example.txt", "Hello, World!");
Checks if a given file path is a regular file.
if (is_file("example.txt")) { // It's a file. }
Opens a new connection to the MySQL server.
$conn = mysqli_connect("localhost", "name", "password", "database");
Performs a query on the database.
$result = mysqli_query($conn, "SELECT * FROM table");
Fetches a result row as an associative array.
$row = mysqli_fetch_assoc($result);
Formats a local time/date.
$current_date = date("Y-m-d H:i:s");
Parses a time string into a Unix timestamp.
$timestamp = strtotime("2022-01-15 12:30:00");
Returns the JSON representation of a value.
$json_data = json_encode($data_array);
Decodes a JSON string into a PHP variable.
$php_data = json_decode($json_data, true);
preg_match(): Performs a regular expression match.
if (preg_match("/pattern/", $subject)) { // Match found. }
Performs a regular expression search and replace.
$new_string = preg_replace("/pattern/", "replacement", $original_string);
urlencode(): URL-encodes a string.
$encoded_string = urlencode("Hello, World!");
Decodes a URL-encoded string.
$decoded_string = urldecode($encoded_string);
Starts a new session or resumes the existing session.
session_start();
Defines a cookie to be sent along with the rest of the HTTP headers.
setcookie("", "Omar Aboubakr", time() + 3600, "/");
Determines if a variable is set and is not NULL.
if (isset($variable)) { // Variable is set. }
Destroys the specified variables.
unset($variable);
Dumps information about a variable.
var_dump($variable);
Checks if a function exists.
if (function_exists("my_function")) { // Function exists. }
complete examples in html with explanation
Let’s provide complete examples in HTML with explanations for some common scenarios.
we ‘ll include PHP code snippets within the HTML code.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP String Functions</title> </head> <body> <?php // Example of using string functions $original_string = "Hello, World!"; $length = strlen($original_string); $new_string = str_replace("World", "PHP", $original_string); ?> <p>Original String: <?php echo $original_string; ?></p> <p>String Length: <?php echo $length; ?></p> <p>Modified String: <?php echo $new_string; ?></p> </body> </html>
Explanation:
strlen(): Calculates the length of the original string.
str_replace(): Replaces “World” with “PHP” in the original string.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP Array Functions</title> </head> <body> <?php // Example of using array functions $my_array = array("Apple", "Banana", "Orange"); $count = count($my_array); array_push($my_array, "Grapes"); $last_element = array_pop($my_array); ?> <p>Original Array: <?php print_r($my_array); ?></p> <p>Array Length: <?php echo $count; ?></p> <p>Modified Array: <?php print_r($my_array); ?></p> <p>Last Element Removed: <?php echo $last_element; ?></p> </body> </html>
Explanation:
count(): Counts the number of elements in the original array.
array_push(): Adds “Grapes” to the end of the original array.
array_pop(): Removes and returns the last element from the modified array.
You can similarly create examples for other categories like Date and Time Functions, JSON Functions, Regular Expression Functions, etc., by incorporating relevant PHP code within the HTML structure.
HTML Form (index.html):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP Application</title> </head> <body> <h1>Welcome to the PHP Application</h1> <form action="process_form.php" method="post"> <label for="name">Name:</label> <input type="text" id="name" name="name" required> <label for="email">Email:</label> <input type="email" id="email" name="email" required> <button type="submit">Submit</button> </form> </body> </html>
Explanation:
The HTML form collects the ‘s name and email.
The form has an action attribute pointing to “process_form.php,” where the form data will be processed.
PHP Processing (process_form.php):
<?php if ($_SERVER["REQUEST_METHOD"] === "POST") { // Retrieve input from the form $name = $_POST["name"]; $email = $_POST["email"]; // Validate and process the input $greeting = generateGreeting($name); $emailStatus = validateEmail($email); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP Application - Result</title> </head> <body> <h1>Result</h1> <?php // Display the personalized greeting if (isset($greeting)) { echo "<p>$greeting</p>"; } // Display email validation status if (isset($emailStatus)) { echo "<p>Email Status: $emailStatus</p>"; } ?> <p><a href="index.html">Go back to the form</a></p> </body> </html> <?php // Function to generate a personalized greeting function generateGreeting($name) { return "Hello, $name! Welcome to our PHP application."; } // Function to validate email function validateEmail($email) { if (filter_var($email, FILTER_VALIDATE_EMAIL)) { return "Valid Email Address"; } else { return "Invalid Email Address"; } } ?>
Explanation:
To use this application, create two files: index.html and process_form.php. Place them in the same directory and open index.html in a web browser.
Enter your name and email in the form, submit it, and you’ll see the personalized greeting and email validation status on the result page.
Here’s a quiz with 20 questions related to the PHP built-in functions lesson. Each question has multiple-choice answers.
Quiz: PHP Built-in Functions
a) Converts a string to lowercase
b) Counts the number of characters in a string
c) Replaces a substring in a string
a) array_push()
b) array_add()
c) add_element()
a) Reads the content of a file
b) Formats a local time/date
c) Decodes a JSON string
a) isset()
b) empty()
c) unset()
a) Reads the content of a file into a string
b) Writes a string to a file
c) Checks if a file exists
a) random_number()
b) generate_random()
c) rand()
a) mysql_open()
b) mysqli_connect()
c) db_connect()
a) Decodes a JSON string
b) Encodes a PHP variable into JSON format
c) Checks if a variable is JSON
a) str_replace()
b) preg_replace()
c) regex_replace()
a) begin_session()
b) session_open()
c) session_start()
a) Rounds a number
b) Returns the absolute value of a number
c) Checks if a number is positive
a) url_decode()
b) decode_url()
c) urldecode()
a) Destroys the specified variables
b) Sets a variable to NULL
c) Initializes a variable
a) mysqli_fetch_array()
b) mysql_fetch_assoc()
c) fetch_row_assoc()
a) Returns the absolute value of a number
b) Rounds a floating-point number to the nearest integer
c) Calculates the square root of a number
a) exists_function()
b) function_exists()
c) check_function()
a) Encodes a string for URL use
b) Decodes a URL-encoded string
c) Checks if a URL is valid
a) write_file()
b) file_put_contents()
c) put_file()
a) Encodes a JSON string
b) Decodes a JSON string into a PHP variable
c) Checks if a variable is JSON
a) Checks if a variable is set and not NULL
b) Checks if a variable is empty
c) Checks if a variable is initialized