Parameters and Arguments

Last updated on

If you're coding in PHP you've most probably come across the terms 'parameters' and 'arguments' in functions. Well, they are pretty significant, and it's important to understand them, otherwise, you'll start scratching your head as to why your function is not operating the way you thought it should.

In this post, I will explain exactly what parameters and arguments are, how they work in PHP, and why that matters for your code. By the time you're done reading this, you'll know how to use them like a pro—including some cool tricks like setting default values and even passing functions as arguments. Yep, that's a thing! You're also going to learn how to avoid some common mistakes so you don't have to spend hours debugging your code. Many exciting things are in store! Let's dive in!

What's the Difference Between Parameters and Arguments?

Okay, let's start with the basic question. A parameter is a placeholder in a function that is 'waiting' for you to provide it with information. An argument is a real value that you give to the function while calling it. More formally: a parameter is like an empty field on a form, and an argument is the data you fill in.

The following figure shows you an example.

Parameters and Arguments

Here’s an example that will make it clear:

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

greeting("Alice");

Above, $name is the parameter. It's like an empty box, just begging to be filled. When you call greeting("Alice"), "Alice" is the argument. It's what gets passed into the function to fill that box. Then the function prints out "Hello, Alice!".

Simple enough, right? Now, let’s move on to the next section and learn how to create parameters and pass arguments in PHP.

Creating Parameters and Passing Arguments in PHP

You write a PHP function by placing its parameters inside the parentheses, like so:

The basic syntax of parameters would be as the below example.

function add($num1, $num2) {
    return $num1 + $num2;
}

Here, $num1 and $num2 are the parameters. When you call the function, you pass in real values—arguments. Thus, doing this:

echo add(5, 10); // Outputs: 15

You're telling the function to take 5 and 10, add them together, and return 15. Easy enough, right? Here's where you have to watch out though: the order of the arguments matters! Mix it up, and your results could be other than what you expected.

Let's see an example of what could go wrong:

function subtract($a, $b) {
      return $a - $b;
}

echo subtract(5, 10); // Outputs: -5

Here, you get -5 because $a takes 5 and $b takes 10. This subtracts 10 from 5—which isn't what you'd expect when you subtract one number from another. Just remember: the order of the arguments matters!

Optional Parameters with Default Values

Sometimes, you won't want to pass arguments to every single parameter in a function, and that's just fine! PHP enables you to declare default values for parameters. This way, if you don't provide an argument, the function will simply use the default.

Here is how it works:


  function is_admin( $is_admin = 0 ) {
 
     $admin = 1;
     
     if ( $admin == $is_admin ) {
       return true;
     }

     return false;
  }

  var_dump( is_admin() ); // bool(false)
  var_dump( is_admin(1) ); // bool(true)

In this example, the default for $is_admin is 0 Therefore, unless one calls this function and actually passes an argument, it will return 0. On the other hand, if someone calls it and provides an argument such as 1.

Important: Put Default Parameters Last

You can have many parameters in a function, but if one has a default value, it must be last. PHP needs to get the required parameters first. If you put them out of order, you'll get an error.

Correct:

// => This has a default value with wrong position
function is_admin( $param1 = " ", $param2, $param3 ) { .. }
  
// Correct position for default value
function is_admin( $param2, $param3,  $param1 = " " ) { .. }

Incorrect:

function sendEmail($subject = "No Subject", $email) {
    // This will give an error
}

Just leave the default ones at the end, and you'll be golden.

Passing Arguments by Reference

Here's a trick: sometimes you want to make a change to a variable inside a function and have that change stick outside the function, too. You can pass an argument by reference.

In PHP, passing by reference allows the function to directly change the value of the variable.

For example.

function increaseByTen(&$num) {
    $num += 10;
}

$myNumber = 5;
increaseByTen($myNumber);
echo $myNumber; // Outputs: 15

In this case, due to the & symbol before $num, any changes to $num inside the function affect $myNumber. Now, after calling increaseByTen($myNumber), $myNumber is 15.

$number = 1;
 function increase_number( &$add_number ) {
    $add_number += 22;
 }
   

 increase_number($number);
 
 echo $number; // 23

Also you can assign values by global variable, which means you will able to change the value of the variable from the function by using global statement.

$counter = 10;

function add_six( $new ) {
  global $counter;
  $counter += $new;
}
  
add_six(20);

echo $counter; // 30

Pass by Value

PHP usually passes arguments by value, meaning that changes made inside the function do not affect the variable outside it.

function increaseByTen($num) {
    $num += 10;
}

$myNumber = 5;
increaseByTen($myNumber);

echo $myNumber; // Outputs: 5

Here, although the function is adding 10 to $num, which was passed in as $myNumber, the value of $myNumber remains the same outside of the function. PHP is using the original value of $myNumber, but it's not changing it.

Variadic Functions and Passing Functions as Parameters

Now, let's get a little fancier. PHP allows you to pass a variable amount of arguments into a function using something called a variadic function. In a nutshell, you can accept as many arguments as you need with the ... operator (ellipses).

function sum(...$numbers) {
    return array_sum($numbers);
}

echo sum(1, 2, 3, 4); // Outputs: 10

In variadic functions, you can pass as many numbers as you want, and PHP will be just fine with that. It's a nice way to make your functions flexible.

Passing Functions as Arguments

And the cool part: you can also pass a function as an argument to another function. It's really useful when you want to apply a certain function to some data.

function applyFunction($func, $value) {
    return $func($value);
}

echo applyFunction('strtoupper', 'hello'); // Outputs: HELLO

Here, strtoupper is the argument passed in and gets applied to the string "hello," converting it into "HELLO." In other words, you're handing your function another tool to work with.

Wrapping Up

Now you should know how parameters and arguments work in PHP. Whether you’re setting defaults, passing by reference, or working with variadic functions these will make your life so much easier. Parameters are placeholders in functions, arguments are the actual values you pass when you call them.

Once you master these basics you’ll save time debugging and write more efficient and flexible code. The more you use these the more natural they’ll become in your everyday coding. So next time you write a PHP function try experimenting with different parameter setups and see how they can make your functions more powerful.

Thank you for reading. Happy Coding!

Frequently Asked Questions (FAQs)

  • What is the difference between a parameter and an argument in PHP?

    A parameter is a placeholder in the function definition, while an argument is the actual value passed to the function when calling it. For example:
    function greet($name) { 
        echo "Hello, $name!"; 
    }
    greet("Alice"); 
    Here, $name is the parameter, and "Alice" is the argument.
  • Can I have default parameters in PHP functions?

    Yes, you can assign default values to parameters. If the argument is not provided when calling the function, the default value will be used. Example:
    function greet($name = "Guest") { 
        echo "Hello, $name!"; 
    }
    
    greet(); // Outputs: Hello, Guest! 
  • What does "pass by reference" mean in PHP?

    Passing by reference means the function can modify the variable passed to it. This is done using the & symbol before the parameter. Example:
    function increaseByTen(&$num) { 
        $num += 10; 
    }
    $myNumber = 5;
    increaseByTen($myNumber); 
    echo $myNumber; // Outputs: 15 
    The original $myNumber variable is changed because it was passed by reference.
  • Can I pass a function as an argument to another function in PHP?

    Yes, you can pass functions as arguments to other functions. Example:
    function applyFunction($func, $value) { 
        return $func($value); 
    }
    echo applyFunction('strtoupper', 'hello'); // Outputs: HELLO
    
    The strtoupper function is passed as an argument and applied to the string "hello".
  • What happens if I pass too many arguments to a PHP function?

    PHP will ignore the extra arguments if they exceed the number of defined parameters. It's best to match the number of arguments to the parameters to avoid confusion.
  • What are variadic functions in PHP?

    Variadic functions allow you to pass an arbitrary number of arguments using the ... operator. Example:
    function sum(...$numbers) { 
        return array_sum($numbers); 
    }
    echo sum(1, 2, 3, 4); // Outputs: 10 
    You can pass as many arguments as you need, and PHP will handle them as an array.
  • Can I have more than one optional parameter in a PHP function?

    Yes, you can have multiple optional parameters. Just make sure to place them at the end of your parameter list so that PHP can assign default values correctly.
  • How do I pass arguments by value in PHP?

    PHP passes arguments by value by default. This means the function works with a copy of the variable, and changes inside the function do not affect the original variable. Example:
    function increaseByTen($num) { 
        $num += 10; 
    }
    $myNumber = 5;
    increaseByTen($myNumber); 
    echo $myNumber; // Outputs: 5 
    The original $myNumber variable remains unchanged because it was passed by value.
Share on: