Open In App

What is a Function in PHP?

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In PHP, a function is a block of code that performs a specific task and can be executed multiple times throughout a script. Functions help in organizing code, promoting reusability, and improving readability by encapsulating a set of instructions under a single name.

Syntax:

// Function declaration
function greet($name) {
return "Hello, $name!";
}

// Function invocation
echo greet("Geeks");

// Output: Hello, Geeks!

Features:

  • Declaration: Functions are made using the function keyword, followed by a name and any needed information in parentheses.
  • Invocation: Once created, functions can be used over and over by simply typing their name and providing any required data inside parentheses.
  • Return Values: Functions can give back information by using the return keyword. This information can be used immediately or stored in a variable for later use.
  • Parameters: Functions can take in variables, called parameters, to work with specific data. These parameters help customize what the function does each time it’s used.
  • Scope: Functions keep their own space for variables, meaning what’s inside a function usually can’t be seen or changed from outside. This keeps things tidy and prevents confusion.
  • Built-in Functions: PHP includes many pre-made functions for common tasks like changing text, working with lists of data, dealing with files, and talking to databases. These make coding faster and easier by providing ready-made solutions.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads