OneBite.Dev - Coding blog in a bite size

Call A Function With Parameter In PHP

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

Understanding how to call a function with a parameter in PHP is crucial for streamlining your code and programming efficiently. This article will provide an easy, step-by-step explanation of how to perform this task.

Code snippet

Below is a simple PHP code snippet showing how to call a function with a parameter:

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

greet("John");
?>

In the code snippet, we first define a function named “greet” which takes one parameter ($name). Then we call this function with an argument (“John”).

Code Explanation

Let’s break this down step by step.

  1. Function Definition

First, we define a function with the keyword function, followed by the name of the function, greet, and the parameter in the brackets ($name).

function greet($name){
   //code to be executed
}

The $name inside the parentheses is a placeholder for a value that will be passed into the function when it is called.

  1. Function Body

Inside the curly braces {} is the code that will be run each time the function is called. In this case, the function outputs a string saying “Hello, ” followed by whatever value is passed in for $name.

{
   echo "Hello, " . $name;
}
  1. Calling the Function

Lastly, the greet function is called using the function name followed by the value you want to pass in in parentheses. In this example, the string “John” is passed in as an argument.

greet("John");

When this code is executed, it will output “Hello, John”.

Knowing how to call a function with a parameter is a fundamental aspect of PHP, and mastering it will assist in a better efficient and organized code. You can pass multiple parameters into a function by separating them with commas, thereby increasing the flexibility and functionality of your code.

php