OneBite.Dev - Coding blog in a bite size

Declare A Function With Single Parameter In PHP

Code snippet for how to Declare A Function With Single Parameter In PHP with sample and detail explanation

PHP, being a server-side scripting language, offers extensive features that simplify the web development process. One of them is the ability to create a function with a single parameter which can be quite useful and can greatly increase the code reusability as well as readability.

Code snippet

To declare a function with a single parameter in PHP, you can use the following code snippet:

<?php
function sayHello($name) {
  echo "Hello " . $name;
}

sayHello("John Doe");
?>

Code Explanation

This code snippet is pretty straightforward and easy to understand. Here is how this works:

  1. The keyword function is used to declare a function in PHP.

  2. sayHello is the name of the function. Function names are case-insensitive and follow the same rules as variable names - they should start with a letter or underscore, followed by any number of letters, numbers, or underscores.

  3. ($name) - This is the parameter for the function. Parameters are like variables, declared inside the parentheses of the function. They are specified after the function name, and their value can be passed when the function is called. In our example, we have used a single parameter $name.

  4. Inside the function, we are using the echo statement to output a string that says ”Hello” followed by the value of the $name parameter.

  5. The function is then called using its name followed by parentheses. Inside the parentheses, we pass the value that we want for the $name parameter. In this case, we passed "John Doe". As a result, Hello John Doe would be printed.

So, this is how a function with a single parameter is declared and used in PHP. You can replace “Hello John Doe” with whatever you like and use this function as per your requirement.

php