A function is a block of code that accomplishes a specific function.
We have user defined and inbuilt functions. User defined functions are created by the user to accomplish certain tasks in a procedural way whereas inbuilt functions were created by the language engineers and made available or documented for use by the programmers. They have already been defined and all a programmer does is to use hem to simplify his/her work.
There are very many inbuilt functions. However, of interest to us in these lesson are a few that we will require later in this series.
Functions can be parametrized or un-parametrized. Parametrized functions has parameters whose arguments are copied when a functions is called. When calling a parametrized function, values must be passed to it for it to do the designated task .
User defined functions example.
Suppose we create a function that receives your name and age and prints them
<?php
//function definition
function printer($name,$age){
echo "Your name is " . $name. " and age: " . $age;
}
//function call
printer("Lewis", 24);
?>
Output: Your name is Lewis and age: 24
You can as well make this function use the return keyword. Change it as shown
<?php
//function definition
function printer($name,$age){
$str = "Your name is " . $name. " and age: " . $age;
return $str;
}
//function call
echo printer("Lewis", 24);
?>
Output: Your name is Lewis and age: 24
Inbuilt functions
I did tell you earlier that I will not cover many inbuilt functions in PHP. Forgive me for that. I am going to show you how to use the following functions because we will need them later in this series.
1. str_replace()
2. explode()
3. array_shift()
4. count()
1. str_replace()
Is a parametrized function that replaces some characters with some other characters in a string.
Syntax
str_replace(find,replace,string,count) where;
Find : Required. Specifies the value to find
Replace: Required. Specifies the value to replace the value in find
String : Required. Specifies the string to be searched
Count : Optional. A variable that counts the number of replacements
This function returns a string (its return type). I will use a relevant example that we will encounter later.
Example
<?php
$mystring = "*188#1*3*3#";
//wherever there is a *, replace it with a #
echo str_replace("#","*",$mystring);
?>
Output: *188*1*3*3*
Did you see that? Ask me a question.
Next function come very soon, faster that you say "Yes Sir!"