PHP functions become more powerful when you **pass arguments** to them. Arguments allow you to provide input values that the function can process and return a result. This makes functions more flexible and reusable!
🔹 What Are Function Arguments?
Arguments are values passed to a function when calling it. They are defined inside parentheses ()
after the function name.
📝 Example 1: Function with One Argument
Let’s create a function that accepts a name and displays a greeting.
<?php function greet($name) { echo "Hello, $name! Welcome to PHP."; } greet("Alice"); // Passing "Alice" as an argument ?>
Explanation:
- The function
greet($name)
accepts one argument,$name
. - When calling
greet("Alice")
,$name
takes the value “Alice”. - The function then prints **”Hello, Alice! Welcome to PHP.”**
📝 Example 2: Function with Multiple Arguments
A function can accept multiple arguments by separating them with commas.
<?php function add($a, $b) { echo "Sum: " . ($a + $b); } add(5, 7); // Passing two arguments ?>
Explanation:
- The function
add($a, $b)
accepts two arguments. - Calling
add(5, 7)
passes the values 5 and 7. - The function calculates and prints **”Sum: 12″.**
📝 Example 3: Function with Default Arguments
If no argument is provided, a default value is used.
<?php function greetUser($name = "Guest") { echo "Hello, $name!"; } greetUser(); // Uses default value "Guest" greetUser("Bob"); // Overrides the default value ?>
Explanation:
- If no argument is passed,
$name
defaults to **”Guest”**. - If an argument is provided (e.g.,
"Bob"
), it replaces the default value.
🎯 Key Takeaways
- Function **arguments** allow input values to be passed and processed.
- **Multiple arguments** can be passed by separating them with commas.
- **Default values** are used when an argument is not provided.
📝 Practice Time!
Try modifying these examples and experiment with different values to see how function arguments work!