PHP Program to Demonstrate Functions (reuse logic without mess)
Learn PHP step by step.
All about PHP - Functions (reuse logic without mess)
Jan 29, 2026
## Chapter 10: Functions (reuse logic without mess)
**Think of functions as recipe cards - write once, use many times!**
**Goal:** Write small functions with clear inputs/outputs, then reuse them confidently.
### What Are Functions? - Your Personal Recipe Collection
**Functions are like recipes in a cookbook - they tell PHP exactly how to do something!**
**Visual Diagram: Function as a Recipe**
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Function Recipe Card β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β βββββββββββββββ ββββββββββββββββ β
β β INPUTS β β FUNCTION β β
β β βββββββββΆβ β β
β β β’ $name β β β’ Do this β β
β β β’ $city β β β’ Then that β β
β β β’ $age β β β’ Finally β β
β βββββββββββββββ ββββββββ¬ββββββββ β
β β β
β ββββββββ΄ββββββββ β
β β OUTPUT β β
β β β β
β β β’ Result β β
β β β’ Answer β β
β β β’ Data β β
β ββββββββββββββββ β
β β
β **Like a coffee machine - put in beans, get coffee!** β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
### Basic Function - Your First Recipe
**The two things that make functions "feel professional" are:**
- **Clear input (parameters)** - what ingredients you need
- **Clear output (return value)** - what dish you get back
```php
<?php
declare(strict_types=1);
function greet(string $name, string $city = "Unknown"): string {
return "Hi " . $name . " from " . $city;
}
echo greet("Kunal", "Indore");
```
**Breaking down the recipe:**
```php
function greet(string $name, string $city = "Unknown"): string {
// ^ ^ ^ ^ ^
// | | | | |
// Name | | | Return type
// | | Default value
// | Parameter type
// Parameters (ingredients)
}
```
### Parameters, Default Values, and Named Arguments
**Default values are like optional ingredients - use them when you don't have everything!**
**Named arguments are like telling the chef exactly what you want - no need to remember the order!**
```php
<?php
declare(strict_types=1);
function priceWithTax(float $price, float $taxPercent): float {
return $price + ($price * $taxPercent / 100);
}
echo priceWithTax(taxPercent: 18, price: 100);
```
**Real-world example with defaults:**
```php
<?php
function createUser(
string $name,
string $email,
string $role = "user",
bool $isActive = true,
string $language = "English"
): array {
return [
"name" => $name,
"email" => $email,
"role" => $role,
"isActive" => $isActive,
"language" => $language
];
}
// Use defaults for most things
$user1 = createUser("John", "john@email.com");
// Override specific defaults
$user2 = createUser(
name: "Sarah",
email: "sarah@email.com",
role: "admin",
language: "Spanish"
);
?>
```
### Return Types - Don't Just Echo Inside
**Return values are like getting a receipt - you can use it later!**
```php
<?php
declare(strict_types=1);
function totalPrice(float $price, int $qty): float {
return $price * $qty;
}
$total = totalPrice(49.50, 3);
echo "Total: $$total"; // Total: $148.5
// Use the result in another calculation
$withTax = $total * 1.18; // Add 18% tax
echo "With tax: $$withTax"; // With tax: $175.23
// Use it in a condition
if ($total > 100) {
echo "You get free shipping!";
}
?>
```
**The difference between echo and return:**
```php
<?php
// Bad: Function that only echoes
function badCalculateArea(float $width, float $height): void {
echo $width * $height;
}
// Good: Function that returns a value
function goodCalculateArea(float $width, float $height): float {
return $width * $height;
}
// With the good version, you can reuse the result!
$area = goodCalculateArea(10, 5);
$totalArea = $area * 4; // Calculate area of 4 rooms
echo "Total area: $totalArea square feet";
?>
```
### Pass by Value vs Pass by Reference
**Pass by value is like giving someone a photocopy - they can write on it, but your original stays the same!**
**Pass by reference is like giving someone your original document - whatever they do affects your original!**
```php
<?php
declare(strict_types=1);
function addPrefix(string $name): string {
$name = "Mr. " . $name;
return $name;
}
$n = "Aman";
echo addPrefix($n);
echo "n";
echo $n;
```
If you want the function to change the original variable (rare, but sometimes useful), pass by reference using `&`.
```php
<?php
declare(strict_types=1);
function normalizeName(string &$name): void {
$name = trim($name);
$name = ucwords(strtolower($name));
}
$name = " riYA shaRMA ";
normalizeName($name);
echo $name;
```
**Visual Diagram: Pass by Value vs Pass by Reference**
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Pass by Value (Default) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β ββββββββββββββββ βββββββββββββββββββ β
β β Original β β Function β β
β β Document β β β β
β β "Aman" β β $name = "Mr. " . $name β
β β β β return "Mr. Aman" β
β β ββββββββββ β β
β β Still β β β β
β β "Aman" β β β β
β ββββββββββββββββ βββββββββββββββββββ β
β β
β **Original stays unchanged - like a photocopy!** β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Pass by Reference β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β ββββββββββββββββ βββββββββββββββββββ β
β β Original β β Function β β
β β Document βββββββββΆβ &$name β β
β β "riYA" β β $name = trim($name) β
β β β β $name = ucwords(strtolower($name)) β
β β ββββββββββ β β
β β Now β β β β
β β "Riya" β β β β
β ββββββββββββββββ βββββββββββββββββββ β
β β
β **Original gets changed - like editing the real document!** β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
### Variadic Functions - Unknown Number of Ingredients
```php
<?php
declare(strict_types=1);
function sum(int ...$nums): int {
return array_sum($nums);
}
echo sum(1, 2, 3, 4);
```
**Variadic functions are like buffet restaurants - you can bring any number of friends!**
```php
<?php
declare(strict_types=1);
function sum(int ...$nums): int {
return array_sum($nums);
}
echo sum(1, 2, 3, 4); // 10
echo sum(5, 10, 15); // 30
echo sum(100); // 100
echo sum(); // 0 (empty sum)
?>
```
**Real-world example - Shopping cart calculator:**
```php
<?php
function calculateTotal(float $taxRate, float ...$prices): float {
$subtotal = array_sum($prices);
$tax = $subtotal * ($taxRate / 100);
return $subtotal + $tax;
}
// Any number of items!
$total1 = calculateTotal(8.5, 10.99, 5.50, 3.25); // 3 items
echo "Total: $$total1n";
$total2 = calculateTotal(8.5, 25.00, 15.00, 8.50, 12.00); // 4 items
echo "Total: $$total2n";
?>
```
### Anonymous Functions and Closures - Your Pocket Tools
**Closures are like carrying a Swiss Army knife - you can use them anywhere you need special logic!**
**Anonymous functions are useful when you need to pass logic into another function (filtering, sorting, mapping).**
```php
<?php
declare(strict_types=1);
$users = [
["name" => "Meera", "age" => 21],
["name" => "Aman", "age" => 17],
["name" => "Rohit", "age" => 30],
];
$adults = array_values(array_filter($users, function (array $u): bool {
return $u["age"] >= 18;
}));
echo json_encode($adults);
```
**Real-world example - Filtering users by age:**
```php
<?php
$users = [
["name" => "Meera", "age" => 21, "city" => "Mumbai"],
["name" => "Aman", "age" => 17, "city" => "Delhi"],
["name" => "Rohit", "age" => 30, "city" => "Bangalore"],
["name" => "Priya", "age" => 25, "city" => "Chennai"],
];
// Filter adults (18+)
$adults = array_values(array_filter($users, function (array $user): bool {
return $user["age"] >= 18;
}));
echo "Adults: " . json_encode($adults, JSON_PRETTY_PRINT) . "n";
// Filter by city
$mumbaiUsers = array_values(array_filter($users, function (array $user): bool {
return $user["city"] === "Mumbai";
}));
echo "Mumbai users: " . json_encode($mumbaiUsers, JSON_PRETTY_PRINT) . "n";
?>
```
**If you want to use a variable from outside inside your closure, use `use` - it's like borrowing ingredients from your kitchen!**
```php
<?php
declare(strict_types=1);
$minAge = 18;
$isAllowed = function (int $age) use ($minAge): bool {
return $age >= $minAge;
};
var_dump($isAllowed(17));
var_dump($isAllowed(21));
```
**Arrow functions are like shortcuts - when you only need one simple thing!**
```php
<?php
declare(strict_types=1);
$nums = [1, 2, 3, 4, 5];
$squares = array_map(fn (int $n): int => $n * $n, $nums);
var_dump($squares); // [1, 4, 9, 16, 25]
// Real-world example: Convert prices to different currency
$pricesUSD = [10.50, 25.00, 15.75, 8.99];
$exchangeRate = 83.5; // USD to INR
$pricesINR = array_map(fn (float $price): float => $price * $exchangeRate, $pricesUSD);
echo "Prices in INR: " . json_encode($pricesINR) . "n";
?>
```
**Common Mistakes with Functions:**
| Mistake | Why It's Wrong | The Right Way |
|---------|----------------|---------------|
| Forgetting return | Function does nothing useful | Always return something useful |
| Echoing inside functions | Can't reuse the result | Return values, echo outside |
| Too many parameters | Hard to remember | Use arrays or objects |
| No type hints | Easy to pass wrong types | Use type declarations |
| No return type | Unclear what function gives back | Specify return types |
**Practice Exercises:**
1. **Temperature Converter**: Create functions to convert between Celsius, Fahrenheit, and Kelvin
2. **Grade Calculator**: Function that takes array of scores and returns letter grades
3. **Password Validator**: Function that checks if password is strong (length, special chars, etc.)
4. **Shopping Cart**: Functions to add items, calculate total, apply discounts
5. **String Formatter**: Functions to format names, phone numbers, addresses
---
## Conclusion
In this article, we explored the core concepts of All about PHP - Functions (reuse logic without mess). Understanding these fundamentals is crucial for any developer looking to master this topic.
## Frequently Asked Questions (FAQs)
**Q: What is All about PHP - Functions (reuse logic without mess)?**
A: All about PHP - Functions (reuse logic without mess) is a fundamental concept in this programming language/topic that allows developers to perform specific tasks efficiently.
**Q: Why is All about PHP - Functions (reuse logic without mess) important?**
A: It helps in organizing code, improving performance, and implementing complex logic in a structured way.
**Q: How to get started with All about PHP - Functions (reuse logic without mess)?**
A: You can start by practicing the basic syntax and examples provided in this tutorial.
**Q: Are there any prerequisites for All about PHP - Functions (reuse logic without mess)?**
A: Basic knowledge of programming logic and syntax is recommended.
**Q: Can All about PHP - Functions (reuse logic without mess) be used in real-world projects?**
A: Yes, it is widely used in enterprise-level applications and software development.
**Q: Where can I find more examples of All about PHP - Functions (reuse logic without mess)?**
A: You can check our blog section for more advanced tutorials and use cases.
**Q: Is All about PHP - Functions (reuse logic without mess) suitable for beginners?**
A: Yes, our guide is designed to be beginner-friendly with clear explanations.
**Q: How does All about PHP - Functions (reuse logic without mess) improve code quality?**
A: By providing a standardized way to handle logic, it makes code more readable and maintainable.
**Q: What are common mistakes when using All about PHP - Functions (reuse logic without mess)?**
A: Common mistakes include incorrect syntax usage and not following best practices, which we've covered here.
**Q: Does this tutorial cover advanced All about PHP - Functions (reuse logic without mess)?**
A: This article covers the essentials; stay tuned for our advanced series on this topic.