PHP Tutorial



FUNCTIONS IN PHP


🧠 PHP Functions

A function in PHP is a reusable block of code that performs a specific task. You define a function once, and you can use (or "call") it multiple times throughout your program.

Think of a function like a machine: You give it input, it processes it, and gives you output.

📌 Benefits of Functions

  • Reduces code repetition
  • Makes code easier to read and manage
  • Improves modularity and reusability

🔧 Defining a Function

<?php
function greet() {
  echo "Hello, World!";
}
greet(); // Calling the function
?>
  

📥 Function with Parameters

You can pass values (parameters) to a function for it to use.

<?php
function greetUser($name) {
  echo "Hello, $name!";
}
greetUser("Alice"); // Output: Hello, Alice!
?>
  

🔁 Function with Return Value

Functions can return values instead of printing them directly.

<?php
function add($a, $b) {
  return $a + $b;
}
$sum = add(5, 3);
echo $sum; // Output: 8
?>
  

⚠️ Default Parameters

You can set default values for parameters if not provided during function call.

<?php
function greetUser($name = "Guest") {
  echo "Hello, $name!";
}
greetUser(); // Output: Hello, Guest!
?>
  

🧩 Built-in vs User-defined Functions

  • User-defined functions: Created by the user using function keyword
  • Built-in functions: Already provided by PHP like strlen(), strtolower(), array_push()
Practice Idea: Create a function that checks if a number is even or odd and returns the result.

📌 Summary

  • Functions save time and reduce repetition
  • They can accept parameters and return values
  • Default values and return types make functions flexible

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review