PHP Parameterized Function

PHP Parameterized functions are the functions with parameters. You can pass any number of parameters inside a function. These passed parameters act as variables inside your function.

They are specified inside the parentheses, after the function name.

The output depends upon the dynamic values passed as the parameters into the function.


PHP Parameterized Example 1

Addition and Subtraction

In this example, we have passed two parameters $x and $y inside two functions add() and sub().

<!DOCTYPE html>  
<html>  
<head>  
    <title>Parameter Addition and Subtraction Example</title>  
</head>  
<body>  
<?php  
        //Adding two numbers  
         function add($x, $y) {  
            $sum = $x + $y;  
            echo "Sum of two numbers is = $sum <br><br>";  
         }   
         add(467, 943);  
  
         //Subtracting two numbers  
         function sub($x, $y) {  
            $diff = $x - $y;  
            echo "Difference between two numbers is = $diff";  
         }   
         sub(943, 467);  
      ?>  
</body>  
</html>  

Output:

PHP Parametrized function 1

PHP Parameterized Example 2

Addition and Subtraction with Dynamic number

In this example, we have passed two parameters $x and $y inside two functions add() and sub().

 

<?php  
//add() function with two parameter  
function add($x,$y)    
{  
$sum=$x+$y;  
echo "Sum = $sum <br><br>";  
}  
//sub() function with two parameter  
function sub($x,$y)    
{  
$sub=$x-$y;  
echo "Diff = $sub <br><br>";  
}  
//call function, get  two argument through input box and click on add or sub button  
if(isset($_POST['add']))  
{  
//call add() function  
 add($_POST['first'],$_POST['second']);  
}     
if(isset($_POST['sub']))  
{  
//call add() function  
sub($_POST['first'],$_POST['second']);  
}  
?>  
<form method="post">  
Enter first number: <input type="number" name="first"/><br><br>  
Enter second number: <input type="number" name="second"/><br><br>  
<input type="submit" name="add" value="ADDITION"/>  
<input type="submit" name="sub" value="SUBTRACTION"/>  
</form>    

Output:

PHP Parametrized function 2

We passed the following number,

PHP Parametrized function 3

Now clicking on ADDITION button, we get the following output.

PHP Parametrized function 4

Now clicking on SUBTRACTION button, we get the following output.

PHP Parametrized function 5

Kotlin Infix Function Call

In this article, you will learn to use infix notation to call a function in Kotlin (with the help of examples).

Before you learn how to create a function having infix notation, let’s explore two commonly used infix functions.

When you use || and && operations, the compiler look up for or and and functions respectively, and calls them under the hood.

These two functions support infix notation.


Example: Kotlin or & and function

fun main(args: Array<String>) {
    val a = true
    val b = false
    var result: Boolean

    result = a or b // a.or(b)
    println("result = $result")

    result = a and b // a.and(b)
    println("result = $result")
}

When you run the program, the output will be:

result = true
result = false

In the above program, a or b instead of a.or(b), and a and b instead of a.and(b) is used. It was possible because these two functions support infix notation.


How to create a function with infix notation?

You can make a function call in Kotlin using infix notation if the function

  • is a member function (or an extension function).
  • has only one single parameter.
  • is marked with infix keyword.

Example: User-defined Function With Infix Notation

class Structure() {

    infix fun createPyramid(rows: Int) {
        var k = 0
        for (i in 1..rows) {
            k = 0
            for (space in 1..rows-i) {
                print("  ")
            }
            while (k != 2*i-1) {
                print("* ")
                ++k
            }
            println()
        }
    }
}

fun main(args: Array<String>) {
    val p = Structure()
    p createPyramid 4       // p.createPyramid(4)
}

When you run the program, the output will be:

      * 
    * * * 
  * * * * * 
* * * * * * * 

Here, createPyramid() is an infix function that creates a pyramid structure. It is a member function of class Structure, takes only one parameter of type Int, and starts with keyword infix.

The number of rows of the pyramind depends on the argument passed to the function.

Kotlin Functions

In this article, you’ll learn about functions; what functions are, its syntax and how to create a user-function in Kotlin.

In programming, function is a group of related statements that perform a specific task.

Functions are used to break a large program into smaller and modular chunks. For example, you need to create and color a circle based on input from the user. You can create two functions to solve this problem:

  • createCircle() Function
  • colorCircle() Function

Dividing a complex program into smaller components makes our program more organized and manageable.

Furthermore, it avoids repetition and makes code reusable.


Types of Functions

Depending on whether a function is defined by the user, or available in standard library, there are two types of functions:

  • Kotlin Standard Library Function
  • User-defined functions

Kotlin Standard Library Function

The standard library functions are built-in functions in Kotlin that are readily available for use. For example,

  • print() is a library function that prints message to the standard output stream (monitor).
  • sqrt() returns square root of a number (Double value)
fun main(args: Array<String>) {

    var number = 5.5
    print("Result = ${Math.sqrt(number)}")
}

When you run the program, the output will be:

Result = 2.345207879911715

Here is a link to the Kotlin Standard Library for you to explore.


User-defined Functions

As mentioned, you can create functions yourself. Such functions are called user-defined functions.


How to create a user-defined function in Kotlin?

Before you can use (call) a function, you need to define it.

Here’s how you can define a function in Kotlin:

fun callMe() {
    // function body
}

To define a function in Kotlin, fun keyword is used. Then comes the name of the function (identifier). Here, the name of the function is callMe.

In the above program, the parenthesis ( ) is empty. It means, this function doesn’t accept any argument. You will learn about arguments later in this article.

The codes inside curly braces { } is the body of the function.


How to call a function?

You have to call the function to run codes inside the body of the function. Here’s how:

callme()

This statement calls the callMe() function declared earlier.

Function call in Koltin

Example: Simple Function Program

fun callMe() {
    println("Printing from callMe() function.")
    println("This is cool (still printing from inside).")
}

fun main(args: Array<String>) {
    callMe()
    println("Printing outside from callMe() function.")
}

When you run the program, the output will be:

Printing from callMe() function.
This is cool (still printing from inside).
Printing outside from callMe() function.

The callMe() function in the above code doesn’t accept any argument.

Also, the function doesn’t return any value (return type is Unit).

Let’s take another function example. This function will accept arguments and also returns a value.


Example: Add Two Numbers Using Function

fun addNumbers(n1: Double, n2: Double): Int {
    val sum = n1 + n2
    val sumInteger = sum.toInt()
    return sumInteger
}

fun main(args: Array<String>) {
    val number1 = 12.2
    val number2 = 3.4
    val result: Int

    result = addNumbers(number1, number2)
    println("result = $result")
}

When you run the program, the output will be:

result = 15

How functions with arguments and return value work?

Here, two arguments number1 and number2 of type Double are passed to the addNumbers() function during function call. These arguments are called actual arguments.

result = addNumbers(number1, number2)

The parameters n1 and n2 accepts the passed arguments (in the function definition). These arguments are called formal arguments (or parameters).

Passing arguments to a function in Kotlin

In Kotlin, arguments are separated using commas. Also, the type of the formal argument must be explicitly typed.

Note that, the data type of actual and formal arguments should match, i.e., the data type of first actual argument should match the type of first formal argument. Similarly, the type of second actual argument must match the type of second formal argument and so on.


Here,

return sumInteger

is the return statement. This code terminates the addNumbers() function, and control of the program jumps to the main() function.

In the program, sumInteger is returned from addNumbers() function. This value is assigned to the variable result.

Return value from a function in Kotlin

Notice,

  • both sumInteger and result are of type Int.
  • the return type of the function is specified in the function definition.// return type is Int fun addNumbers(n1: Double, n2: Double): Int { … .. … }

If the function doesn’t return any value, its return type is Unit. It is optional to specify the return type in the function definition if the return type is Unit.


Example: Display Name by Using Function

fun main(args: Array<String>) {
    println(getName("John", "Doe"))
}

fun getName(firstName: String, lastName: String): String = "$firstName $lastName"

When you run the program, the output will be:

John Doe

Here, the getName() function takes two String arguments, and returns a String.

You can omit the curly braces { } of the function body and specify the body after = symbol if the function returns a single expression (like above example).

It is optional to explicitly declare the return type in such case because the return type can be inferred by the compiler. In the above example, you can replace

fun getName(firstName: String, lastName: String): String = "$firstName $lastName"

with

fun getName(firstName: String, lastName: String) = "$firstName $lastName"

Python Functions

In this article, you’ll learn about functions, what a function is, the syntax, components, and types of functions. Also, you’ll learn to create a function in Python.

What is a function in Python?

In Python, a function is a group of related statements that performs a specific task.

Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.

Furthermore, it avoids repetition and makes the code reusable.

Syntax of Function

def function_name(parameters):
	"""docstring"""
	statement(s)

Above shown is a function definition that consists of the following components.

  1. Keyword def that marks the start of the function header.
  2. A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python.
  3. Parameters (arguments) through which we pass values to a function. They are optional.
  4. A colon (:) to mark the end of the function header.
  5. Optional documentation string (docstring) to describe what the function does.
  6. One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).
  7. An optional return statement to return a value from the function.

Example of a function

def greet(name):
    """
    This function greets to
    the person passed in as
    a parameter
    """
    print("Hello, " + name + ". Good morning!")

How to call a function in python?

Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function we simply type the function name with appropriate parameters.

>>> greet('Paul')
Hello, Paul. Good morning!

Note: Try running the above code in the Python program with the function definition to see the output.

def greet(name):
    """
    This function greets to
    the person passed in as
    a parameter
    """
    print("Hello, " + name + ". Good morning!")

greet('Paul')

Docstrings

The first string after the function header is called the docstring and is short for documentation string. It is briefly used to explain what a function does.

Although optional, documentation is a good programming practice. Unless you can remember what you had for dinner last week, always document your code.

In the above example, we have a docstring immediately below the function header. We generally use triple quotes so that docstring can extend up to multiple lines. This string is available to us as the __doc__ attribute of the function.

For example:

Try running the following into the Python shell to see the output.

>>> print(greet.__doc__)

    This function greets to
    the person passed in as
    a parameter

The return statement

The return statement is used to exit a function and go back to the place from where it was called.

Syntax of return

return [expression_list]

This statement can contain an expression that gets evaluated and the value is returned. If there is no expression in the statement or the return statement itself is not present inside a function, then the function will return the None object.

For example:

>>> print(greet("May"))
Hello, May. Good morning!
None

Here, None is the returned value since greet() directly prints the name and no return statement is used.


Example of return

def absolute_value(num):
    """This function returns the absolute
    value of the entered number"""

    if num >= 0:
        return num
    else:
        return -num


print(absolute_value(2))

print(absolute_value(-4))

Output

2
4

How Function works in Python?

How function works in Python?
Working of functions in Python

Scope and Lifetime of variables

Scope of a variable is the portion of a program where the variable is recognized. Parameters and variables defined inside a function are not visible from outside the function. Hence, they have a local scope.

The lifetime of a variable is the period throughout which the variable exits in the memory. The lifetime of variables inside a function is as long as the function executes.

They are destroyed once we return from the function. Hence, a function does not remember the value of a variable from its previous calls.

Here is an example to illustrate the scope of a variable inside a function.

def my_func():
	x = 10
	print("Value inside function:",x)

x = 20
my_func()
print("Value outside function:",x)

Output

Value inside function: 10
Value outside function: 20

Here, we can see that the value of x is 20 initially. Even though the function my_func() changed the value of x to 10, it did not affect the value outside the function.

This is because the variable x inside the function is different (local to the function) from the one outside. Although they have the same names, they are two different variables with different scopes.

On the other hand, variables outside of the function are visible from inside. They have a global scope.

We can read these values from inside the function but cannot change (write) them. In order to modify the value of variables outside the function, they must be declared as global variables using the keyword global.


Types of Functions

Basically, we can divide functions into the following two types:

  1. Built-in functions – Functions that are built into Python.
  2. User-defined functions – Functions defined by the users themselves.