13 January 2011

Php For Beginners (Lesson 8)

In this lesson we will discuss functions in php. A function is a block of code which is declared once on a page and then used each time it is needed in the script. For example if you are using some piece of code repetitively in your script then you can declare a function and place that code in the function. Now each time you need to use that code you don’t need to write the whole code again, instead you just call the function and your code will be called automatically.

There are two types of functions:

· Built-in Functions

· User Defined functions

Built-in Functions
Built-in Functions are those functions which are stored by default in php. Php has 700 built-in functions.

Example

  • strtolower(); Converts string to lowercase
  • strtoupper(); Converts string to upper case
  • exit(); Stops the execution of script

User Defined Functions
User defined functions are thoses functions which are declared by users for their own use.

Creating a function in php

A function should always be declared before it is going to be called.

Syntax

Function func_name (parameter1,parameter2,…..,parametern)

{ code to be executed. }

Example 1 (Function without parameters)

In this example we will create a function that takes no parameters and returns no value. This function will only prints our name on the screen.
<?php 
function display_name () 
{ 
   echo "Bill"; 
} 
echo "Hi there! My name is "; 
display_name(); 
?> 
The output of the above example will be “Hi there! My name is Bill”.

Example 2 (Function with parameters)

In this example we will create a function with a parameter. This function will take name as parameter when it is called an then display that name on the screen.
<?php 
function display_name ($name) 
{ 
   echo $name; 
} 
echo "Hi there! My name is "; 
display_name('Bill'); 
echo " and my brother's name is "; 
display_name('Jack'); 
?> 
The output of the above example will be “Hi there! My name is Bill and my brother's name is Jack”.

Example 3 (Function which returns value)

In this example we will create a function which returns some value. This function will take two numbers as parameter and returns the average.
<?php 
function average($num1,$num2) 
{ 
   $result=($num1 + $num2)/2; 
   return $result; 
} 
echo "The Average of 20 & 100 is ".average('20','100'); 
?> 
The output of this example will be “The Average of 20 & 100 is 60”.

Ok guys this is all about the functions in php. For any queries feel free to comment.


next Previous Lesson --- Next Lesson next

1 comment:

Anonymous said...

Wow, nice script dude, really liked it.