PHP

Functions In PHP

  • A block of code for specific tasks.
  • Save compile time –only compile once.
  • Reuse many times when needed.
  • Optimize your code.

Built-in functions like print(); date();

  • User-defined functions:
  • Function names cannot have spaces.
  • Function name must begin with letter or underscore.

E.g., call a built-in function abs();

<?php
$num=-5;
$new_num=abs($num);
echo $new_num;
?>

Declaring a Function

function function_name(arguments)
{
block of codes and statements;
}
  • You can declare a function below a call to it.
  • May have none, one, or multiple arguments each separated by a comma.
  • Write function name followed by ( ), even if the function doesn’t have any arguments.

Example-

<?php
function print_br($str) {
print "$str <br>";
}
print_br("line1");
print_br("line2");
?>

Functions – Return Value

  • Functions may have a return value.
  • A return value in a function, returns the value to the function that may be used later on while calling a function.
  • You may need to access the value that the function returns, but you may not need to print it out, that’s why you use a return value for a function.

Example-Functions – Return Value

<?php
function multiply_by_two($value){
$result=$value*2;
return $result;
}
echo multiply_by_two(7);
?>

Example-Functions – Without Return Value

<?php
function multiply_by_two($value){
$result=$value*2;
echo $result;
}
multiply_by_two(7);
?>

PHP built-in Functions
Sqrt(); — Take the square root of a number
Ceil(); — Take ceil of a decimal number
Floor(); — take the floor of a decimal number
Max(); — take the max number
Min(); — take the min number
Strtolower(); — convert string to lower case
Strtoupper(); — convert string to upper case

Recommended Tutorials for you


Related posts

How to convert number to String in PHP

Anuj Kumar

PHP Constants

Anuj Kumar

Server Side form Validation in PHP

Anuj Kumar

JQuery Ajax Tutorial – Learn About Developing Effective Next Generation Web Application

Anuj Kumar

PHP Constants

Anuj Kumar

How to append a string in PHP

Anuj Kumar

PHP Prepared Statements

Anuj Kumar

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

This site uses Akismet to reduce spam. Learn how your comment data is processed.