Function basically a block of statements. In PHP there are 2 types of functions – User-defined functions & Pre-defined functions.
We saw many examples before about Pre-defined functions. Ex –
- strlen() function helps to display length of a string.
- gettype() function helps to print the data-type of current variable.
- str_word_count() function helps to count words inside a full string.
- strrev() function helps to reverse any string.
Let’s see some built-in function uses…
- Built-in(Pre-defined) functions
PHP has near about 1000 or more built-in functions, which makes a web-developers life easy.
Let’s see one of the usages of built-in function below.
File – code1.php
<?php // gettype() helps to print datatype of any variable $var=20; echo gettype($var); $var=[1,2,3]; echo “<br>”; echo gettype($var); // str_word_count() helps to count words inside a full string $str=”tiger is an animal which eats meat”; echo ‘<br>total words ‘.str_word_count($str); // strrev() helps t reverse a string $str2=”computer”; echo “<br>real string: $str2”; $str2=strrev($str2); echo “<br>reverse string: $str2”; ?> |

- User-defined Functions
Besides the built-in PHP functions, it is possible to create your own functions. A function is a block of statements that can be used repeatedly in a program. A function will not execute automatically when a page loads. A function will be executed by a call to the function.
Let’s see the, basic function declare, define & call
File – code2.php
<?php // function ‘f1()’ declare & define function f1(){ echo ‘simple function!’; } // function ‘f1()’ call f1(); ?> |

Remember: We can call a function up to ‘n’ number of times.
File – code3.php
<?php function f1(){ echo ‘<font color=”red”><br>simple function!</font>’; } // calling function ‘f1()’ upto 3 times below f1(); f1(); f1(); ?> |
