🔧 Lesson 6 :- Functions in PHP

 Functions in PHP



A function is a reusable block of code that performs a specific task. You define it once and can call it many times to reduce repetition and improve code structure.

🧠 Why Use Functions?

  • To avoid repeating code
  • To break programs into smaller, manageable parts
  • To make your code reusable and more readable

🧱 Basic Function Syntax

function functionName($parameter1, $parameter2, ...) {
  // code block
}
  

✅ Example 1: Simple User-Defined Function

function greet() {
  echo "Hello, World!";
}

greet(); // Output: Hello, World!
  

✅ Example 2: Function with Parameter

function greetUser($name) {
  echo "Hello, $name!";
}

greetUser("Alice"); // Output: Hello, Alice!
  

✅ Example 3: Function with Return Value

function add($a, $b) {
  return $a + $b;
}

echo add(5, 3); // Output: 8
  

📚 Types of Functions in PHP

🧑‍💻 1. User-Defined Functions

You create these yourself using the function keyword.

function square($number) {
  return $number * $number;
}

echo square(5); // Output: 25
  

⚙️ 2. Built-in Functions

PHP comes with hundreds of built-in functions for strings, arrays, files, math, etc.

👉 Example: strlen()
$text = "PHP is fun";
echo strlen($text); // Output: 10
  
👉 Example: strtoupper()
$name = "php";
echo strtoupper($name); // Output: PHP
  
👉 Example: isset()
$age = 25;
if (isset($age)) {
  echo "Variable is set."; // Output: Variable is set.
}
  

🔄 Default Parameter Values

You can set default values for parameters so they’re optional when calling the function.

function greet($name = "Guest") {
  echo "Welcome, $name!";
}

greet();        // Output: Welcome, Guest!
greet("John");  // Output: Welcome, John!
  

💡 Best Practices

  • Use clear and descriptive names for functions
  • Keep functions short and focused on a single task
  • Use return values when results need to be reused
  • Group common logic into functions for reuse

Post a Comment

0 Comments