A PHP function is a piece of code that can be reused many times. It can take input as an argument list and return value.
In PHP, we can define
We can declare and call user-defined functions easily. Let us see the syntax to declare user-defined functions.
Syntax
function functionname(){
//code to be executed
}
Note: The function name must start with a letter and underscore only like other labels in PHP. It can not start with numbers or special symbols.
File Name: function_file.php
<?php
function myFunction(){
echo "Hello PHP Function";
}
myFunction();//calling function
?>
Output: Hello PHP Function
We can pass the information in the PHP function through arguments that are separated by a comma.
PHP supports
Let us see the example to pass a single argument in the PHP function.
File Name: function_arg.php
<?php
function myFunction($user_name){
echo "Hello $user_name<br/>";
}
myFunction("Kamal");
myFunction("Sonia");
myFunction("Rani");
?>
Output:
Hello Kamal
Hello Sonia
Hello Rani
Let us see the example to pass two arguments in a PHP function.
File Name: function_args.php
<?php
function getRecord($username,$age){
echo "Hello $username, you are $age years old<br/>";
}
getRecord("Kamal",27);
getRecord("Sonia",18);
getRecord("Shivani",23);
?>
Output:
Hello Kamal, you are 27 years old
Hello Sonia, you are 18 years old
Hello Shivani, you are 23 years old
We can specify a default argument value in the function. While calling PHP function if you do not specify any argument, it will take the default argument. Let us see a simple example of using the default argument value in the PHP function.
Example of default Argument Value
Let us see an example of PHP function that returns a value.
File Name: function_defaultarg.php
<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
Output: Cube of 3 is: 27
© 2024 Easy To Learning. All Rights Reserved | Design by Easy To Learning