PHP Default Arguments 🎯

beginner
25 min

PHP Default Arguments 🎯

Welcome to CodeYourCraft's PHP Default Arguments tutorial! In this lesson, we'll explore how to use default arguments in PHP functions. This is a practical, beginner-friendly guide, so let's get started!

What are Default Arguments? πŸ“

Default arguments are values assigned to function parameters when the function is called without providing an argument. These values are used when the function is called without passing an argument or when an argument is passed as null or undefined.

Why Use Default Arguments? πŸ’‘

Default arguments make functions more flexible and easier to use. They allow functions to behave differently based on the input provided, and they reduce the need for conditional checks within the function.

Defining Functions with Default Arguments πŸ“

Let's create a simple function with a default argument:

php
function greet($name = "World") { echo "Hello, $name!"; }

In this example, the $name parameter has a default value of "World". When we call the greet() function, we can either pass a name or let it use the default value:

php
greet(); // Output: Hello, World! greet("Alice"); // Output: Hello, Alice!

Note πŸ“

In PHP, default arguments must be assigned after non-default arguments. You can't assign a default value to a parameter that has already been defined without a default value.

Advanced Example 🎯

Let's create a more complex example that demonstrates how default arguments can make a function more flexible:

php
function calculateArea($length, $width = 1, $height = null) { $area = 0; // Calculate area based on the provided parameters if (!is_null($height)) { $area = $length * $width * $height; } else { $area = $length * $width; } echo "The area is: $area"; }

In this example, we have a function called calculateArea() that can calculate the area of a rectangle or a cuboid. The $length parameter is required, while $width and $height are optional.

php
calculateArea(5); // Output: The area is: 5 calculateArea(5, 4); // Output: The area is: 20 calculateArea(5, 4, 3); // Output: The area is: 60

Quiz 🎯

Quick Quiz
Question 1 of 1

What is the purpose of default arguments in PHP functions?

Quick Quiz
Question 1 of 1

In PHP, where should default arguments be defined in a function?