PHP Named Arguments vs. Positional Arguments

The PHP named arguments are the names of the arguments through which the values are passed, allowing you to add a name for the argument beside the value, and that can be separated with a colon (:).

    Let’s see an example.

    function that_is_func( $val1, $val2 ) {
        echo $val1 . "this is a" . $val2;
    }
    
    rename_it(
      val2: "PHP Tutorial",
      val1: "CodedTag, " 
    );

    So, you don’t need to fill the function arguments in order. Anyway, this feature appeared in PHP 8. Before that, we were using the function arguments by order.

    Let’s understand how it works.

    How Named Arguments Work in PHP

    Let’s say you have a function that’s like a recipe. In the old days, you had to add ingredients in the exact order the recipe said. First flour, then sugar, and so on. But what if you could just name the ingredients as you added them? That’s named arguments for you.

    Here is an example:

    // Old way: Just hope you remember the order right
    mixCake('2 cups', '1 cup', '3 large');
    
    // New way with named arguments: Much clearer!
    mixCake(flour: '2 cups', sugar: '1 cup', eggs: '3 large');

    So, you don’t have to remember the order of arguments anymore. Just name them, and you’re good to go. However, If a function lets you skip adding salt because not everyone likes it, named arguments make this easy. You just mention the ingredients you care about.

    Additionally, you can mix named arguments with the old-school way if you want. Just remember to keep the unnamed (positional) arguments first.

    PHP produces an error when named arguments are positioned incorrectly. Let’s understand this to avoid errors during the execution.

    Incorrect Positioning of Named Arguments in PHP

    Mixing up the order by putting a named argument before positional ones doesn’t work. PHP gets confused and throws an error. It’s like trying to read a sentence backward. PHP just can’t understand it.

    Let’s see an example.

    function concate_strings( $string, $value, $delimiter ) {
        return $string . $delimiter .  $value;
    }

    In this example, I will alter the positions of the arguments after assigning a name to only the last parameter.

    concate_strings(
      delimiter: ',',
      "string 1",
      "value 2"
    );

    This will show you the following error.

    Fatal error: Cannot use positional argument after named argument in /file/path/name.php on line 9

    Named arguments make your code cleaner and easier to read. It’s like writing a clearer recipe that anyone can follow, even if they start in the middle. So the correct code is like the below.

    concate_strings(
       "string 1",
       "value 2",
       delimiter: ','
    );

    In the following part, you will see additional examples to gain a deeper understanding.

    Examples of Named arguments

    Let’s say you have a function to greet someone. Before, you did this: Imagine trying to remember what goes where.

    greet('Hello', 'John', 'Doe');

    Now, you just say what each thing is.

    greet(greeting: 'Hello', firstName: 'John', lastName: 'Doe');

    Or creating a link in your webpage:

    // Before: What does each '' mean again?
    echo createLink('Click here', '', '', '_blank');
    
    // Now: It's like telling a story
    echo createLink(text: 'Click here', target: '_blank');

    Anyway, Let’s summarize it.

    Wrapping Up

    Named arguments in PHP 8 are like giving names to stars. Before, you just pointed and hoped others saw the same star you did. Now, you just say, “Look at Orion’s Belt,” and everyone knows exactly where to look. It makes coding clearer, less error-prone, and honestly, just more fun.

    So, there you have it: a simpler take on PHP 8’s named arguments. It’s all about making your code as easy to read as a good book, where every character (or argument) plays a clear role.

    Thank you for reading. Happy Coding!

    Similar Reads

    PHP require_once and require

    Essentially, “require” and “require_once” are directives in PHP to include and evaluate a specific file during the execution of a…

    PHP array_any: How it Works with Arrays with Examples

    PHP 8.4 released the array_any to test if at least one element matches a condition. Understand the array_any Function in…

    PHP MySQL Create Database: MySQLi & PDO Examples

    If you are working with PHP and MySQL, one of the first tasks you may need is to create a…

    PHP array_intersect_assoc: How it Works with Examples

    PHP array_intersect_assoc compares values and keys in arrays. It returns matches with the same key and value from all arrays…

    PHP Elvis Operator: How (?:) Works with Examples

    The Elvis operator in PHP is a shorthand version of the ternary operator. PHP allows developers to use this conditional…

    PHP array_intersect_key Function: How it Works with Examples

    The array_intersect_key in PHP compares arrays by keys and returns only the parts that match. It is useful when you…

    PHP array_diff_assoc: How to Compare Arrays with Keys

    Array values may look the same, but keys can differ. The array_diff_assoc in PHP finds differences by both values and…

    filter_has_var Function: Check if Input Exists in PHP

    User input does not always come through as expected. Sometimes values are missing or not set at all. This can…

    PHP $_REQUEST: Learn How to Capture User Inputs

    Today, we will discuss the most prominent and useful superglobal in PHP, $_REQUEST, to get user input. The $_REQUEST array lets you retrieve…

    Mastering PHP’s Do-While Loop: Examples and Explanation

    The PHP do-while loop is a type of loop that executes a block of code at least once, and then…

    Previous Article

    PHP Variadic Functions: Use Unlimited Arguments

    Next Article

    PHP Callable & Callback: Pass a Function to Another

    Write a Comment

    Leave a Comment

    Your email address will not be published. Required fields are marked *


    Subscribe to Get Updates

    Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
    No spam. Unsubscribe anytime.